Spring @value用法示例详解

2022-09-03 15:22:40 59 0
魁首哥

目录

  • 一、两种使用方法
  • 二、配置
    • 2.1 @Value(“#{configProperties[‘key’]}”)使用
      • 2.1.1配置文件:
    • 2.2 @Value(“${key}”)使用
      • 2.2.1 配置文件

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

Spring @value用法示例详解

一、两种使用方法

1、@Value(“#{configProperties[‘key’]}”)

2、@Value(“${key}”)

二、配置

2.1 @Value(“#{configProperties[‘key’]}”)使用

2.1.1配置文件:

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

配置方法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(“${keandroidy}”)使用

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>clphpasspath:value.properties</value>
        </array>
    </property>
</bean>

ValueDemo.java

@Component
public class ValueDemo {
    @Value("${key}")
    private String value;

    public String getValue() {
        return value;
    }
}

到此这篇关于Spring-@value用法详解的文章就介绍到这了,更多相关Spring @value内容请搜索我们以前的文章php或继续浏览下面的相关文章希望大家以后多多支持我们!

收藏
分享
海报
0 条评论
59
上一篇:图解Java中归并排序算法的原理与实现 下一篇:源码分析SpringMvc日志打印被忽略输出问题

本站已关闭游客评论,请登录或者注册后再评论吧~

忘记密码?

图形验证码