properties文件讀取-Spring方式


一、properties文件讀取思路

在web環(huán)境下,Spring的ApplicationContext是容器管理的(不僅管理been,還有properties屬性文件),通過ContextLoaderListener載入。要獲取ApplicationContext需要先得到ServletContext,而得到ServletContext又要先獲取session。而且每一個要使用ApplicationContext的地方都要這么做。

但是,通過擴展ContextLoaderListener,我們可以很方便的獲取到ApplicationContext

原理十分簡單,ContextLoaderListener類里面有一個叫做contextlnitialized的方法,這個方法用于初始化context

二、操作步驟

我們自己寫一個SpringPropertyResourceReader工具類,里面有一個靜態(tài)變量applicationContext,用來存放web環(huán)境下的ApplicationContext的引用,getProperty(key)的方法就可以讀取Spring中加載屬性文件的內(nèi)容了。

1、先寫SpringPropertyResourceReader類:

public class SpringPropertyResourceReader {
    private static ApplicationContext applicationContext;

    //private static ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    static Properties properties = new Properties();

    public static ApplicationContext getContext() {
        return applicationContext;
    }

    public static void setContext(ApplicationContext aContext) {
        applicationContext = aContext;
    }

    private static void init() {
        AbstractApplicationContext abstractContext = (AbstractApplicationContext) applicationContext;

        try {
            // get the names of BeanFactoryPostProcessor
            String[] postProcessorNames = abstractContext.getBeanNamesForType(BeanFactoryPostProcessor.class,
                    true, true);

            for (String ppName : postProcessorNames) {
                // get the specified BeanFactoryPostProcessor
                BeanFactoryPostProcessor beanProcessor = (BeanFactoryPostProcessor) abstractContext.getBean(ppName,
                        BeanFactoryPostProcessor.class);

                // check whether the beanFactoryPostProcessor is 
                // instance of the PropertyResourceConfigurer
                // if it is yes then do the process otherwise continue
                if (beanProcessor instanceof PropertyResourceConfigurer) {
                    PropertyResourceConfigurer propertyResourceConfigurer = (PropertyResourceConfigurer) beanProcessor;

                    // get the method mergeProperties 
                    // in class PropertiesLoaderSupport
                    Method mergeProperties = PropertiesLoaderSupport.class.getDeclaredMethod(
                            "mergeProperties");
                    // get the props
                    mergeProperties.setAccessible(true);

                    Properties props = (Properties) mergeProperties.invoke(propertyResourceConfigurer);

                    // get the method convertProperties 
                    // in class PropertyResourceConfigurer
                    Method convertProperties = PropertyResourceConfigurer.class.getDeclaredMethod("convertProperties",
                            Properties.class);
                    // convert properties
                    convertProperties.setAccessible(true);
                    convertProperties.invoke(propertyResourceConfigurer, props);
                    properties.putAll(props);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getProperty(String propertyName) {
        if ((applicationContext != null) && properties.isEmpty()) {
            init();
        }

        if (applicationContext == null) {
            return null;
        }

        return properties.getProperty(propertyName);
    }
}


2、然后再寫ContextLoaderListener的擴展類MyContextLoaderListener

public class MyContextLoaderListener extends ContextLoaderListener {
    @Override
    public void contextInitialized(ServletContextEvent event) {
        super.contextInitialized(event);

        ServletContext context = event.getServletContext();

        // 獲取web環(huán)境下的ApplicationContext
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        //  將ApplicationContext,set到SpringPropertyResourceReader的靜態(tài)變量context
        SpringPropertyResourceReader.setContext(ctx);
    }
}

3、在web.xml里面配置spring監(jiān)聽器,用我們剛剛擴展好的MyContextLoaderListener替換以前的ContextLoaderListener:

yourpackage.MyContextLoaderListener

4、在applicationContext.xml中配置加載屬性文件的代碼

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:scan/job.properties</value> 
        </list>
    </property>
</bean>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,578評論 19 139
  • 今天內(nèi)容概述 Spring框架的概述 SpringIOC的快速入門 IoC容器XML的方式 在web項目中集成Sp...
  • Spring容器高層視圖 Spring 啟動時讀取應(yīng)用程序提供的Bean配置信息,并在Spring容器中生成一份相...
    Theriseof閱讀 2,919評論 1 24
  • 夢里江南煙雨稠 酒醒窗外游啊游 山外青山樓外樓 越過鴻壑又一溝 煙雨已逝樓空在 獨留一人亦徘徊 醉復(fù)求醉愁復(fù)愁 明...
    深度Wanys閱讀 243評論 0 0

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