先声明,写到properties配置文件的变量名最好具有特殊性
新建test.properties配置文件,内容如下
com.name=wx5f559450f4170318
一种是使用spring提供的一个标签,可以简单配置,如下
<context:property-placeholder location="classpath:test.properties"/>
配置多个properties通过分号隔开在后面添加即可,例如
<context:property-placeholder location="classpath:test.properties,classpath:jdbc.properties"/>
另一种是通过注到bean的属性来进行配置,这里也是配置多个,如下
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:test.properties</value>
</list>
</property>
</bean>
这两种配置,在java类里面获取properties文件里面的值,都是可以通过注解@value(${key})来获取的
@Value("${com.name}")
private String name;
除此之外,还有一种方式,和上面的第二种非常相似;不过这里不推荐使用,一般使用上面的两种即可。
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:test.properties</value>
</list>
</property>
</bean>
通过这种配置方式,必须指定bean的id名称,否则取不到值。
要通过@value(“#{beanName.key}”)来获取值,但这种配置方式不能获取xxx.xxx的值,也就是说
@Value("#{prop.com.name}")
private String name;
这是获取不到值的。
把properties文件改成
com_Name=wx5f559450f4170318
这样就能获取值了
@Value("#{prop.com_Name}")
private String name;
后来,我发现在第三种配置方式的基础上,再加上下面的配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="prop"/>
</bean>
就能同样地通过注解@value(${key})来获取值,这样配置未免太累赘了,所以还是推荐使用前面两种。