这篇文章主要介绍了Spring-@value用法详解,为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性,本文通过实例代码给大家介绍的非常详细,需要的朋友参考下吧
为了简化读取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-@value用法详解的文章就介绍到这了,更多相关Spring @value内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:Spring @value用法示例详解
- JSP 制作验证码的实例详解 2023-07-30
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- Java实现顺序表的操作详解 2023-05-19
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- 深入了解Spring的事务传播机制 2023-06-02
- JSP页面间传值问题实例简析 2023-08-03
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- Java中的日期时间处理及格式化处理 2023-04-18
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06