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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值