Spring通过@Value注解自动导入配置文件的几种方式

本文介绍了Spring框架中使用@Value注解从属性文件加载配置的多种方法,包括通过PropertyPlaceholderConfigurer、PreferencesPlaceholderConfigurer和PropertiesFactoryBean。同时强调在使用@Value时,需为注入的属性提供对应的setter方法。示例代码展示了如何直接注入字面量值。
场景

假如有以下属性文件dev.properties, 需要注入下面的tag

tag=123

需要声明的是:在使用@Value 注解 注入参数时,在当前类需要给该属性提供Setter 方法!!

1.通过PropertyPlaceholderConfigurer
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="dev.properties" />
</bean>

代码:

@Value("${tag}")
private String tag;

2.通过PreferencesPlaceholderConfigurer

<bean id="appConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="location" value="dev.properties" />
</bean>

代码:

@Value("${tag}")
private String tag;

与上面 PropertyPlaceholderConfigurer 用法 相同!

3.通过PropertiesFactoryBean

   <bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="dev.properties" />
    </bean>

代码:

@Value("#{config['tag']}")
private String tag;
通过util:properties

效果同PropertiesFactoryBean一样

代码:

@Value("#{config['tag']}")
private String tag;
其他方式

有时也可以不通过文件,直接写字面量

<bean id="appConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <!--<property name="location" value="classpath:${env}.properties" />-->
    <property name="properties">
        <props>
            <prop key="tag">123</prop>
        </props>
    </property>
</bean>

代码:

@Value("${tag}")
private String tag;
另外还有一种方式:
Spring中有个<context:property-placeholder location=""/>标签,可以用来加载properties配置文件,location是配置文件的路径,我们现在在工程目录的src下新建一个conn.properties文件,里面写上上面dataSource的配置:

<context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 --> 
   <context:property-placeholder location=""/>标签也可以用下面的<bean>标签来代替,<bean>标签我们更加熟悉,可读性更强
<!-- 与上面的配置等价,下面的更容易理解 -->  
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 -->  
        <array>  
            <value>classpath:conn.properties</value>  
        </array>  
    </property>  
</bean>  
  虽然看起来没有上面的<context:property-placeholder location=""/>简洁,但是更加清晰,建议使用后面的这种。但是这个只限于xml的方式,即在beans.xml中用${key}获取配置文件中的值value。




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值