您的位置:首页 > 编程语言 > Java开发

Spring注解@Value及属性加载配置文件

2017-12-08 09:26 302 查看
Spring中使用@Value注解给bean加载属性的配置文件有两种使用方式

第一种:使用@Value("#{configProperties['websit.msgname']}")

spring中配置属性加载文件的配置方式

<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:/properties/websit.properties</value>
</list>
</property>
</bean>
注意

1.这里使用的configProperties必须要和定义的bean名称一致。

2.websit用来指定msgname来源于那个配置文件

3.配置的加载属性bean名称为org.springframework.beans.factory.config.PropertiesFactoryBean

第二种:使用@Value("${websit.msgname}");

使用这种方式,又可以有两种配置方式

方式一

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>

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


方式二

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/websit.properties</value>
</list>
</property>
</bean>

当使用@Value注解bean属性时,如果没有在配置文件中配置,这时启动spring就会抛出异常。@Value提供了一种默认值的设置方式,如果在属性文件中没有配置则可以使用默认值。形式如下

@Value("${avg.age:22}")
private int userAge;

如果使用@Value注解后,数据不能正常的被注入则需要在xml的配置文件中加入下列代码

<context:annotation-config/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐