read properties

读取配置文件在项目中使用频率很大,但是实际项目中各种人,各种用法,五花八门,往往是一种方式的各种变体,然很多种方式是其中一种方式的复杂化.今天我来总结下读取配置文件的集中方式及一些不能靠copy代码能理解的一些缘由.

这里变量other要有get/set方法,不然抛此异常

BeanExpressionContext' - maybe not public?

注入配置文件需要使用@PropertySource指定文件地址

若使用@Value还需要配置一个PropertySourcesPlaceholderConfigurer的bean,这个bean 可以在属性使用类中进行配置,同时也可以在配置文件中进行配置,如果两个地方或者多次配置则出现如下异常

Could not resolve placeholder

在spring3中增加ignore-unresolvable="true"来解决

<context:property-placeholder location="yyy.properties" ignore-unresolvable="true"/>

<context:property-placeholder location="xxx.properties" ignore-unresolvable="true"/>

 在spring2.5中,<context:property-placeholder > 没有ignore-unresolvable属性,这时可以用PropertyPlaceholderConfigurer

 <bean id="propertyConfig"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:redis_config.properties</value>
            </list>
            
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true" />  
    </bean>

配置文件中的使用方式在上述注释的代码里作用相同

使用Environment读取,只需声明来源@PropertySource("classpath:test.properties"),注入Environment

原文地址:https://www.cnblogs.com/yangfei-beijing/p/6212838.html