Spring注解@Value

Spring @Value 注解详解

本文参考自: https://blog.youkuaiyun.com/ryelqy/article/details/77453713

 

@Value能让我们在java代码中使用property文件的属性,使用@Value有两种形式:

1、@Value("#{configProperties['t1.msgname']}")

2、@Value("${t1.msgname}")

 

这两种形式,最大的区别在于配置:

1、

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

备注:configProperties是此bean的id,可自定义,并不是说一定得是configProperties

PropertiesFactoryBean 加载Properties文件的工厂类

 

2、@Value("${t1.msgname}")的配置既可以在1的基础上扩展,也能完全自己配置

扩展方式:

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

备注:核心是PreferencePlaceholderConfigurer 可以理解为最优先的选择

 

自己配置:

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

------------------------------------------------------

 

前提:

1、当前类使用@Component或由@Component扩展开来的注解,

2、xml文件内配置了是通过pakage扫描包

<context:component-scan base-package="pakage_name"/>

 

-------------------------------------------------------

 

spring boot中使用

spring boot中,我们只需要在application.properties中添加属性即可使用,spring boot已配置好上述一切

转载于:https://www.cnblogs.com/yanze/p/10641196.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值