spring boot中獲取profile
阿新 • • 發佈:2018-12-20
spring boot與profile
spring boot 的專案中不再使用xml的方式進行配置,並且,它還遵循著
靜態獲取方式
靜態工具類獲取當前專案的profile環境。
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import java.util.Locale; /** * */ /** * @author wangjiuzhou (
[email protected]) * @date 2018/10/27 * 專案名稱: * 類名: SpringContextUtil * 描述: 獲取bean的工具類,可用於線上程裡面獲取bean */ @Component public class SpringContextUtil implements ApplicationContextAware { public static final String LOCAL_PROFILE = "local"; public static final String DEV_PROFILE = "dev"; public static final String TEST_PROFILE = "test"; public static final String PRO_PROFILE = "pro"; private static ApplicationContext context = null; /* (non Javadoc) * @Title: setApplicationContext * @Description: spring獲取bean工具類 * @param applicationContext * @throws BeansException * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } // 傳入執行緒中 public static <T> T getBean(String beanName) { return (T) context.getBean(beanName); } // 國際化使用 public static String getMessage(String key) { return context.getMessage(key, null, Locale.getDefault()); } // 獲取當前環境 public static String getActiveProfile() { return context.getEnvironment().getActiveProfiles()[0]; } }
點評:
- 這種方式在使用起來很方便也是現在各個部落格文章所撰寫的方式,在很多Service的業務程式碼中使用起來很方便,畢竟是靜態的方式嘛!
- 但是有一種缺陷,因為實現ApplicationContextAware介面,而spring中的這個介面是在所有的Bean注入完畢,才會執行setApplicationContext方法,那麼問題來了,往往在專案中我們可能會對一些Bean進行一些config操作,例如:@Bean注入,而有時候我們會根據不同的profile進行不同的定製化config。這個時候恰恰我們的工具類SpringContextUtil還沒有執行setApplicationContext
autowire ProfileConfig
使用這種方式首先宣告一下,其實就相當於一個特殊的configBean一樣,因為只有這樣,這個類才不會在所有bean全部載入完畢後才能獲取到context。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
/**
* @author wangjiuzhou ([email protected])
* @date 2018/11/07
*
* 獲取當前專案環境:local、dev、test、pro
*/
@Configuration
public class ProfileConfig {
public static final String LOCAL_PROFILE = "local";
public static final String DEV_PROFILE = "dev";
public static final String TEST_PROFILE = "test";
public static final String PRO_PROFILE = "pro";
@Autowired
private ApplicationContext context;
public String getActiveProfile() {
return context.getEnvironment().getActiveProfiles()[0];
}
}
點評:
- ProfileConfig ,首先是作為一個相當於Bean的形式存在著,此處的不在解釋@configuration和@component的區別;
- 注入ApplicationContext因為該介面extends於EnvironmentCapable,所以可以獲取到環境的一些資訊;