import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component(value = "applicationContextUtils")
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext context;//应用上下文
//本类维护自己注册到IOC容器的Bean
private static ApplicationContextUtils applicationContextUtils;
@Value(value = "${spring.application.name}")
private String applicationName;//应用名
@Value(value = "${server.port}")
private String serverPort;//服务器端口号
@Value(value = "${server.servlet.context-path}")
private String contextPath;//应用上下文访问前缀
private static String serverInfo;//服务器信息
private static final Class<ApplicationContextUtils> CLASS = ApplicationContextUtils.class;
public static String getContextPath(){
if (applicationContextUtils == null){
applicationContextUtils = getBean(CLASS);
}
return applicationContextUtils.contextPath;
}
public static String getServerInfo(){
if (serverInfo == null){
if (applicationContextUtils == null){
applicationContextUtils = getBean(CLASS);
}
serverInfo = applicationContextUtils.applicationName+"_"+applicationContextUtils.serverPort;
}
return serverInfo;
}
public static String getApplicationName(){
if (applicationContextUtils == null){
applicationContextUtils = getBean(CLASS);
}
return applicationContextUtils.applicationName;
}
public static String getServerPort(){
if (applicationContextUtils == null){
applicationContextUtils = getBean(CLASS);
}
return applicationContextUtils.serverPort;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext(){
return context;
}
public static<T> T getBean(Class<T> clazz){
T result = null;
if (context != null){
result = context.getBean(clazz);
}
return result;
}
}
import com.wpq.service.IServiceA;
import com.wpq.service.IServiceB;
import com.wpq.service.IServiceC;
//玩转IOC
public class ServiceHolder {
//全部为接口
private static IServiceA serviceA;
private static IServiceB serviceB;
private static IServiceC serviceC;
public static IServiceA getServiceA() {
if (serviceA == null){
serviceA = ApplicationContextUtils.getBean(IServiceA.class);
}
return serviceA;
}
public static IServiceB getServiceB() {
if (serviceB == null){
serviceB = ApplicationContextUtils.getBean(IServiceB.class);
}
return serviceB;
}
public static IServiceC getServiceC() {
if (serviceC == null){
serviceC = ApplicationContextUtils.getBean(IServiceC.class);
}
return serviceC;
}
}
本文地址:https://blog.csdn.net/weixin_43766298/article/details/107394847
如对本文有疑问, 点击进行留言回复!!
Springboot项目因为kackson版本问题启动报错解决方案
Java多线程下的其他组件之CyclicBarrier、Callable、Future和FutureTask详解
网友评论