From 27b2df3069de9a8ee0e3dd3b2455a7ef1b90a45e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B7=E5=86=B7?= <2270033969@qq.com> Date: Sun, 1 Sep 2024 13:29:31 +0800 Subject: [PATCH] =?UTF-8?q?feat(core):=20SpringContextHolder=20=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E7=8E=AF=E5=A2=83=E5=88=A4=E6=96=AD=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/core/util/SpringContextHolder.java | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/SpringContextHolder.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/SpringContextHolder.java index 7c85c2d9..46b59659 100755 --- a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/SpringContextHolder.java +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/SpringContextHolder.java @@ -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; + } + }