Spring-@value用法详解

为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性。

一、两种使用方法

1、@Value("#{configProperties['key']}")

2、@Value("${key}")

二、配置

2.1 @Value("#{configProperties['key']}")使用

2.1.1配置文件:

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

   2.配置方法2:  

<util:properties id="configProperties" location="classpath:value.properties"></util:properties>  

注:配置1和配置2等价,这种方法需要util标签,要引入util的xsd:

http://www.springframework.org/schema/util

http://www.springframework.org/schema/util/spring-util-3.0.xsd"

value.properties:

key=1  

ValueDemo.java:

复制代码
@Component  
public class ValueDemo {  
    @Value("#{configProperties['key']}")  
    private String value;  
  
    public String getValue() {  
        return value;  
    }  
}  
复制代码

 

2.2 @Value("${key}")使用

2.2.1 配置文件

1、在2.1.1的配置文件基础上增加:

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

 

2、直接指定配置文件,完整的配置:

 
复制代码
<bean id="appProperty"  
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations">  
        <array>  
            <value>classpath:value.properties</value>  
        </array>  
    </property>  
</bean>  

或者:
<bean id="appProperty"  
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations" value="classpath:value.properties" />  
</bean>


或者:
需要添加命名空间:
xmlns:context="http://www.springframework.org/schema/context"

<beans profile="test"> //profile 用于方便切换测试和正式环境不同的配置文件,需要在web.xml配置

<context:property-placeholder location="/WEB-INF/springConf/test/*.properties" ignore-unresolvable="true"/> //加载该路径下的所有配置文件

</beans>

<context:property-placeholder location="classpath:value.properties" ignore-unresolvable="true"/> //加载某一个配置文件


复制代码

 

ValueDemo.java:

复制代码
@Component  
public class ValueDemo {  
    @Value("${key}")  
    private String value;  
  
    public String getValue() {  
        return value;  
    }  
}  
复制代码

转载:https://blog.csdn.net/u010832551/article/details/73826914

posted @   迷走神经  阅读(893)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示