Spring Java 注解配置之 properties文件注入

全局配置文件注入

由于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.classServletWebConfig.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;
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容