全局配置文件注入
由于Spring存在2個應用上下文,一個是WebApplicationContext,另一個是ServletApplicationContextInitializer。它們兩者之間有的bean實例是不通用的。比如本文要使用PropertyPlaceholderConfigurer類實例。
第一步、配置文件掃描
將properties文件都放在classpath下,可以自定義目錄。例如我就放在了resources/config目錄下,主要是為了自己方便查找。

image.png
使用PropertiesFactoryBean掃描全部的properties文件。
/** 加載配置文件 */
@Bean("propertiesBean")
public PropertiesFactoryBean propertiesFactoryBean() throws IOException {
PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
factoryBean.setLocations(ResourceUtil.getResources("classpath:config/*.properties"));
return factoryBean;
}
其中ResourceUtil是自己根據(jù)PathMatchingResourcePatternResolver封裝的一個工具類,主要是為了代碼整潔。源碼如下:
public class ResourceUtil {
public static Resource getResource(String location) {
return resolver().getResource(location);
}
public static Resource[] getResources(String locationPattern) throws IOException {
return resolver().getResources(locationPattern);
}
public static PathMatchingResourcePatternResolver resolver() {
return new PathMatchingResourcePatternResolver();
}
}
第二步、將配置注入應用上下文
使用PropertyPlaceholderConfigurer將配置內(nèi)容注入上下文,該bean必須是static方法,否則啟動會異常告警。
由于開始說了spring mvc 存在2個應用上下文,所以在使用該類進行配置注入的時候需要分別在ServletRootConfig.class和ServletWebConfig.class中都要寫上該方法。
/** 注入配置文件 */
@Bean("propertyPlaceholderConfigurer")
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(@Qualifier("propertiesBean") Properties properties) throws IOException {
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
configurer.setProperties(properties);
return configurer;
}
第三步、使用配置內(nèi)容
有了以上配置后,你就可以在 Service、Controller 等任意bean中使用@Value注解注入properties文件的配置了。
eg:
@Value("${value}")
private String value;