Spring@value用法示例详解

发布时间:2022-8-25 09:24

为了简化读取properties文件中的配置值,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.properties</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(“${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>

ValueDemo.java

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

public String getValue() {
return value;
}
}
Spring Security注销设置的方法 生活杂谈

Spring Security注销设置的方法

Spring Security中也提供了默认的注销配置,在开发时也可以按照自己需求对注销进行个性化定制 开启注销 默认开启 package com.example.config; imp...
spring-boot-maven-plugin 配置有啥用 生活杂谈

spring-boot-maven-plugin 配置有啥用

这篇文章主要介绍了spring-boot-maven-plugin 配置是干啥的,这个是SpringBoot的Maven插件,主要用来打包的,通常打包成jar或者war文件,本文通过示例代码给大家介绍...
Spring AOP底层机制之代理模式 网站建设

Spring AOP底层机制之代理模式

为什么要学习代理模式,因为AOP的底层机制就是动态代理! 代理模式: 静态代理动态代理 学习aop之前 , 我们要先了解一下代理模式! 静态代理 静态代理角色分析 ...