spring 中如何读取properties的中属性信息

来源:互联网 发布:php怎么读 编辑:程序博客网 时间:2024/06/05 05:51

1.spring 中提供了一个可以获取properties文件属性的类。PropertyPlaceholderConfigurer类

下面的一个实例是通过继承该类来获取文件的属性值。

1.声明一个类:CustomizedPropertyConfigurer

    private static Map<String, Object> ctxPropertiesMap;    @Override    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {        super.processProperties(beanFactory, props);        // load properties to ctxPropertiesMap        ctxPropertiesMap = new HashMap<String, Object>();        for (Object key : props.keySet()) {            String keyStr = key.toString();            String value = props.getProperty(keyStr);            ctxPropertiesMap.put(keyStr, value);        }    }    // static method for accessing context properties    public static Object getContextProperty(String name) {        return ctxPropertiesMap.get(name);    }

getContextProperty(String name)可以直接通过properties中的属性键值就可以获取值。

声明一个监听器:在容器初始化的时候获取属性文件的值,放置到context中。

public class ContextCommonDataListener implements ServletContextListener {    private ServletContext context = null;    public ContextCommonDataListener() {    }    @Override    public void contextInitialized(ServletContextEvent event) {        this.context = event.getServletContext();        String basePath = Toolkits.getServerBasePath();        context.setAttribute("basePath", basePath);        log.info("ContextCommonDataListener,获取服务器basepath:" + basePath);        String footerhtml = (String) CustomizedPropertyConfigurer.getContextProperty("footer.html");        context.setAttribute("footer", footerhtml);    }    @Override    public void contextDestroyed(ServletContextEvent event) {        this.context = null;    }}

最后直接在页面上使用ER表达式就可以获取该属性文件的内容。

0 0