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

来源:互联网 发布:北京海量数据怎么样 编辑:程序博客网 时间:2024/06/04 23:18

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/>



阅读全文
0 0