目的:简化项目中properties配置文件的读取。
解决方案:Spring提供了@Value的方式读取,可以简化项目的配置。
1.@Value
Spring配置文件(方式一)
<context:property-placeholder ignore-resource-not-found="true" local-override="true" location="classpath*:properties/*.properties" />`
Spring配置文件(方式-,使用绝对路径)
<context:property-placeholder
location="file:${user.dir}/Notes/conf/datasource.properties,
file:/Users/Notes/conf/db2.properties"
ignore-unresolvable="true" />
Spring配置文件(方式二)
<bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/application.properties</value>
<value>classpath:config/redis.properties</value>
</list>
</property>
</bean>
java bean配置(方式一)
@Component("bean")
public class Bean {
// properties配置文件的key: encrypt.desKey
// #{null}} 如果配置文件没有key时,默认值是null;
@Value("${encrypt.desKey:#{null}}")
private String desKey;
public String getDesKey() {
return desKey;
}
public void setDesKey(String desKey) {
this.desKey = desKey;
}
}
javabean配置(方式二)
@Component("bean")
public class Bean {
//spring的配置,bean Id='configProperties'
@Value("#{configProperties['key']}")
private String desKey;
public String getDesKey() {
return desKey;
}
public void setDesKey(String desKey) {
this.desKey = desKey;
}
}