properties文件读取-Spring方式


一、properties文件读取思路

在web环境下,Spring的ApplicationContext是容器管理的(不仅管理been,还有properties属性文件),通过ContextLoaderListener载入。要获取ApplicationContext需要先得到ServletContext,而得到ServletContext又要先获取session。而且每一个要使用ApplicationContext的地方都要这么做。

但是,通过扩展ContextLoaderListener,我们可以很方便的获取到ApplicationContext

原理十分简单,ContextLoaderListener类里面有一个叫做contextlnitialized的方法,这个方法用于初始化context

二、操作步骤

我们自己写一个SpringPropertyResourceReader工具类,里面有一个静态变量applicationContext,用来存放web环境下的ApplicationContext的引用,getProperty(key)的方法就可以读取Spring中加载属性文件的内容了。

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环境下的ApplicationContext
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        //  将ApplicationContext,set到SpringPropertyResourceReader的静态变量context
        SpringPropertyResourceReader.setContext(ctx);
    }
}

3、在web.xml里面配置spring监听器,用我们刚刚扩展好的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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,054评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,404评论 19 139
  • 今天内容概述 Spring框架的概述 SpringIOC的快速入门 IoC容器XML的方式 在web项目中集成Sp...
  • Spring容器高层视图 Spring 启动时读取应用程序提供的Bean配置信息,并在Spring容器中生成一份相...
    Theriseof阅读 7,814评论 1 24
  • 梦里江南烟雨稠 酒醒窗外游啊游 山外青山楼外楼 越过鸿壑又一沟 烟雨已逝楼空在 独留一人亦徘徊 醉复求醉愁复愁 明...
    深度Wanys阅读 1,462评论 0 0