spring 注入properties到bean

很多情况下,项目的配置放在properties文件中是更合适的,而放在不是静态变量里。比如邮箱配置,外部接口地址等。之前我们是通过自己写帮助类,通过Properties对象的load方法去加载文件,然后把值放在map里,供全局使用。在spring3以后,可以通过@Value标签往bean里注入。下面将会讲解@Value读取properties文件的方式。

 

1. 首先,applicationContext.xml文件中引入命名空间。

<beans>标签的xsi:schemaLocation加入:

http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd

 

2. 声明org.springframework.beans.factory.config.PropertiesFactoryBean,并设置properties文件

在applicationContext.xml文件中加入:

<bean id="settings" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
    <property name="locations">
        <list>
            <value>classpath*:/test.properties</value>
        </list>
    </property>
</bean>

 

3. 在classpath路径创建test.properties文件

内容:

TEST=from test.properties

 

4. 在bean里注入TEST

@Value("#{settings['TEST']}")
private String test;

这个属性不需要get set方法。

猜你喜欢

转载自lzxhll.iteye.com/blog/2215644