feat(core): SpringContextHolder 增加环境判断工具类

This commit is contained in:
冷冷 2024-09-01 13:29:31 +08:00
parent 9627260cf7
commit 27b2df3069

View File

@ -22,7 +22,9 @@ import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
/**
@ -32,10 +34,12 @@ import org.springframework.stereotype.Service;
@Slf4j
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
public class SpringContextHolder implements ApplicationContextAware, EnvironmentAware, DisposableBean {
private static ApplicationContext applicationContext = null;
private static Environment environment = null;
/**
* 取得存储在静态变量中的ApplicationContext.
*/
@ -43,6 +47,14 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
return applicationContext;
}
/**
* 获取环境
* @return {@link Environment }
*/
public static Environment getEnvironment() {
return environment;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@ -87,6 +99,14 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
applicationContext.publishEvent(event);
}
/**
* 是否是微服务
* @return boolean
*/
public static boolean isMicro() {
return environment.getProperty("spring.cloud.nacos.discovery.enabled", Boolean.class, true);
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@ -96,4 +116,9 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
SpringContextHolder.clearHolder();
}
@Override
public void setEnvironment(Environment environment) {
SpringContextHolder.environment = environment;
}
}