跳至主要內容

配置文件值注入

Jin大约 5 分钟

配置文件值注入

1、两种方式

  1. @Value(“”)
  2. @ConfigurationProperties

2、@Value

@Value注解只能接收一个字符串参数,但有三种使用方式:

  1. @Value(“123”) 直接注入字符串值,如果类型不同会尝试自动类型转换
  2. @Value(“${}”) 外部配置文件注入
    • 若找不到对应的配置,则会提示 Could not resolve placeholder
  3. @Value(“#{}”) spel 方式,此方式会从javabean对象中取值注入属性

找不到bean则会触发异常:

·org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field ‘***’ cannot be found on object of type ‘org.springframework.beans.factory.config.BeanExpressionContext

3、@ConfigurationProperties

告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;

3.1、yml

person:
    lastName: hello
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists:
      - lisi
      - zhaoliu
    dog:
      name: 小狗
      age: 12

3.2、javaBean

prefix = “person”:配置文件中哪个下面的所有属性进行一一映射,多级的用"."分隔

@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
}

3.3、配置文件处理器

我们可以导入配置文件处理器,以后编写配置就有提示了

<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>

3.4、@EnableConfigurationProperties

@EnableConfigurationProperties(Person.class)

注意:如果没有使用 @EnableConfigurationProperties 注解,我们可能会在 @ConfigurationProperties 注解的类上看到 idea 提示报错:

未通过 @EnableConfigurationProperties 注册、标记为 Spring 组件或通过 @ConfigurationPropertiesScan 扫描 

@EnableConfigurationProperties 注解的作用是:使使用 @ConfigurationProperties 注解的类生效。

说明:

如果一个配置类只配置@ConfigurationProperties 注解,使用 @ConfigurationProperties@Component,将properties 配置文件转化的bean@EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。

3.5、松散绑定

@ConfigurationProperties 可以松散绑定,即yaml里写first-name,java用驼峰式命名

松散绑定(Relaxed binding)

比如user: userName也可以表示为user: user-name(大写用-符号),user: username表示为user: user_name(小写用_符号),任然可以绑定到相关

java类中的属性,而不用在配置文件中写出大小写。

3.6、配置文件注入值数据校验

@Validated
@Data
// 指定配置中的路径前缀,并忽略无效字段。
@ConfigurationProperties(prefix = "jwt")
// 指定配置文件路径
@PropertySource(value = "classpath:/jwt.yml", factory = YamlPropertySourceFactory.class, encoding = "UTF-8")
public class JwtProperties {

    private String header = "Authorization"; // HTTP 报头的认证字段的 key

    private String prefix = "Bearer "; // HTTP 报头的认证字段的值的前缀

    private String key = "jin";

    private String refreshKey = "jin";

    /**
     * Access Token 过期时间,单位秒
     */
    @Min(5L)
    private long accessTokenExpireTime;

    /**
     * Refresh Token 过期时间,单位秒
     */
    @Min(5L)
    private long refreshTokenExpireTime;

    private long ttl;
}

spring-boot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。

3.7、@PropertySource:加载指定的配置文件;

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
 *  @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

3.8、@ImportResource

导入Spring的配置文件,让配置文件里面的内容生效;

Spring Boot里面没有Spring的配置文件,就算我们自己编写的配置文件,也不能自动识别;

想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上

@ImportResource(locations = {"classpath:beans.xml"})
导入Spring的配置文件让其生效

来编写Spring的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloService" class="com.jin.service.HelloService"></bean>
</beans>

SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式

3.9、@Configuration

使用**@Bean**给容器中添加组件

/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
 *
 * 在配置文件中用<bean><bean/>标签添加组件
 *
 */
@Configuration
public class MyAppConfig {

    //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService02(){
        System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }
}

3.10、多模块

多模块开发下,被依赖模块的配置可以在依赖他的模块中统一编写

如 jin 项目中,manager模块依赖common模块。common模块虽然有读取配置文件的类,却没有配置文件;

配置文件在manager模块中配置

4、@Value获取值和@ConfigurationProperties获取值比较

@ConfigurationProperties@Value
功能批量注入配置文件中的属性一个个指定
松散绑定(松散语法)支持不支持
SpEL不支持支持
JSR303数据校验支持不支持
复杂类型封装支持不支持
  1. 如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
  2. 如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;
贡献者: Jin