之前的博客中提到过如何通过 java.util.ResourceBundle 和 java.util.Properties 类通过读取 key-value 文件的形式实现常量功能。其实 spring 已经通过 @Value 注解实现,下面看看如何使用。
1.创建.properties文件:
在如下目录创建 keyvalue.properties 文件 src/main/resources/META-INF/spring/keyvalue.properties ,写入如下内容:
test.value=iloveyou
2.配置文件中将.properties文件引入:
在applicationContext.xml 配置文件中加入如下内容:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath*:META-INF/spring/*.properties</value> </list> </property> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties"/> </bean>
这里需要注意的是两个<bean> 的 id 都可以自定义,第一个<property> 中指定 .properties 文件的路径,第二个<property> 中的 ref 要和第一个<bean> 的 id 对应。
3.使用@Value注解:
引入Value 类,在需要取值的属性上方加上 @Value 注解,其中注明的 configProperties 和第一个 <bean> 中的 id 和第二个 <property> 中的 ref 属性对应,[] 中对应 .properties 文件中相应的 key 值:
import org.springframework.beans.factory.annotation.Value;
@Value("#{configProperties['test.value']}")
private String testValue;
System.out.println("TestValue Is: " + testValue);
// 输出结果 Test Value Is: iloveyou
传送门:
《工作积累(二)——使用java.util.ResourceBundle和java.util.Properties实现常量功能》
转载于:https://blog.51cto.com/xitongjiagoushi/1659051