zoukankan      html  css  js  c++  java
  • Spring获取properties文件中的属性

    1.前言

    本文主要是对这两篇blog的整理,感谢作者的分享 
    Spring使用程序方式读取properties文件 
    Spring通过@Value注解注入属性的几种方式

    2.配置文件

    application.properties

    socket.time.out=1000

    3.使用spring代码直接载入配置文件,获取属性信息

    代码如下:

    Resource resource = new ClassPathResource("/application.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);

    4.使用@Value注解获取属性

    4.1 使用PropertyPlaceholderConfigurer

    spring配置

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:application.properties" />
    </bean>

    代码

    @Value("${socket.time.out}")
    int socketTimeout;

    4.2 使用PropertiesFactoryBean

    Spring配置

    <bean id="application" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:application.properties" />
    </bean>

    代码

    @Value("#{$application['socket.time.out']}")
    int socketTimeOut;

    4.3 备注:

    如果将代码部署到resin容器,使用4.1的方法,在程序启动时,总是报无法将”${socket.time.out}”转换成整数的错误。这说明程序并没有找到对应的配置属性。但是在进行单元测试的使用使用ApplicationContext时,则能够找到对应的属性。这可能是在容器里面使用的是WebApplicationContext的问题吧。目前还没有找到确切的原因,现在这里mark一下。 
    使用4.2的方式,部署之后能够获取对应的属性值。

    https://blog.csdn.net/wlfighter/article/details/52563605

     
  • 相关阅读:
    安卓学习Day11
    J2EE-Day09-Servlet
    J2EE-Day08-Tomcat
    安卓学习Day10
    安卓学习Day09
    安卓学习Day08
    安卓学习Day07
    安卓学习Day06
    YII 1.0 常用CURD写法
    php 封装原生数据导出的方法(csv文件格式)和csv文件中长数字自动变成科学计数法的处理
  • 原文地址:https://www.cnblogs.com/0xcafedaddy/p/8999135.html
Copyright © 2011-2022 走看看