Spring @Value简化配置文件的读取
1、在applicationContext.xml文件中配置properties文件
<bean id="appProperty"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:app.properties</value>
</array>
</property>
</bean>
或者简易的操作
<context:property-placeholder location="classpath*:*.properties" />
2、在bean中使用@value注解获取配置文件的值
import org.springframework.beans.factory.annotation.Value;
@Value("${test.string:null}")
private String testStr;
Import a list from properties file
@Value("#{'${server.name:baidu,google,yahoo}'.split(',')}")
private List<String> servers;
Import a map from properties file
application.properties:
property.map={first:value, second:value}
then in Java code you can:
@Value("#{${property.map}}")
Map<String, String> map;
else
@Value("#{'${dmin.details.fields}'.split(',')}")
private List<String> fields;
private Map<String, String> fieldsMap;
@PostConstruct
public void init() {
fieldsMap = new HashMap<String, String>();
if (fields != null && fields.size() != 0) {
for (String field : fields) {
String[] splittedField = field.split(",");
fieldsMap.put(splittedField[0], splittedField[1]);
}
}
}