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方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值