在spring中,有多种配置、使用Properties的方式。
准备属性文件
在resurces下增加dev/config.properties文件,添加内容:1
server.name=gxj
util:properties
配置:
| 1 | <util:properties id="config" location="classpath:dev/config.properties"/> | 
bean 配置方式1
2
3
4<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
<bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:dev/config.properties"/>
</bean>
读取:
| 1 | @Value("#{config['server.name']}") | 
或者在xml配置中读取:1
2
3<bean id="name" class="java.lang.String">
  <constructor-arg value="#{config['server.name']}"/>
</bean>
注意:1
2
3ConfigurableEnvironment environment = context.getEnvironment();
//name为null
String name = environment.getProperty("server.name")
结果为null。
context:property-placeholder
配置:
| 1 | <context:property-placeholder location="classpath:dev/config.properties"/> | 
如果有多个配置文件,用,隔开:1
<context:property-placeholder location="classpath:dev/config.properties,classpath:dev/config1.properties"/>
bean 配置方式:1
2
3<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="classpath:dev/config.properties"/>
</bean>
多个配置文件使用locations属性:1
2
3
4
5
6
7
8<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
    <list>
      <value>classpath:dev/config.properties</value>
      <value>classpath:dev/config1.properties</value>
    </list>
  </property>
</bean>
读取:
| 1 | @Value("${server.name}") | 
或者在xml配置中读取:1
2
3<bean id="name" class="java.lang.String">
  <constructor-arg value="${pro.name}"/>
</bean>
同样,直接用ConfigurableEnvironment获取为null。
@PropertySource方式
| 1 | @Component | 
使用这种方式可以使用Environment 获取属性。