Spring @Value读取配置文件

时间:2025-02-13 13:30:58

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

一、 @value的两种使用方式:

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

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

 

二、配置

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

  • 配置文件:

配置方法1:

<bean class="">

<property name="locations">

<list>

<value>classpath:</value>

</list>

</property>

</bean>

配置方法2:

<util:properties location="classpath:"></util:properties>

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

/schema/util

/schema/util/spring-util-3."

  • 配置文件内容

key=1

  • 文件

@Component

public class ValueDemo {

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

private String value;

public String getValue() {

return value;

}

}

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

  • 配置文件:

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

<bean class="">

<property name="properties" ref="configProperties"/>

</bean>

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

<bean

class="">

<property name="locations">

<array>

<value>classpath:</value>

</array>

</property>

</bean>

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

/schema/util

/schema/util/spring-util-3."

  • 配置文件内容

key=1

  • 文件

@Component

public class ValueDemo {

@Value("${key}")

private String value;

public String getValue() {

return value;

}

}

三、调用方式

在需要获取配置文件值的文件中直接引入该类即可(注意:不是new这个类)

如:

@Autowired

private ValueDemo valueDemo;