Spring boot 配置文件参数映射到配置类属性

参考文章】:SpringBoot之@EnableConfigurationProperties分析

【参考文章】:在Spring Boot中使用 @ConfigurationProperties 注解, @EnableConfigurationProperties

1. pom

        <!-- 通过资源文件注入属性配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

2. main方法上添加注解

  @EnableConfigurationProperties(配置类1.class)

  @EnableConfigurationProperties({配置类1.class,配置类2.class})

  该注解是用来开启对@ConfigurationProperties注解配置Bean的支持,也就是@EnableConfigurationProperties注解告诉Spring Boot 能支持@ConfigurationProperties。

@SpringBootApplication
@EnableConfigurationProperties(SystemConfig.class)
public class BootApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BootApplication.class, args);
        System.out.println("start ok");
    }

3. 配置类

  配置参数在 application.yml 文件中,系统自动读取该文件,所以不必指定配置文件;

  @ConfigurationProperties (prefix = "system",ignoreInvalidFields = false ,ignoreUnknownFields = true) 

  prefix :表示参数 key 的前缀;

  ignoreInvalidFields :忽略无效的属性,默认为 false;

  ignoreUnknownFields :忽略未知的属性,默认为 true;

  如果需要指定配置文件,则需要使用添加 @PropertySource 注解(测试时读取不到配置文件,待解决);

  @PropertySource(value = "filepath",encoding = "utf8",ignoreResourceNotFound = false)

  value:文件路径;

  encoding:文件编码格式;

  ignoreResourceNotFound:忽略未找到的资源文件,默认为false;

@ConfigurationProperties(prefix = "system")
public class SystemConfig  {
    private Integer type;

    public SystemConfig() {
        System.out.println("SystemConfig");
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }
}

4. 配置文件

4.1 yml 文件

system:
  type: 2

4.2 properties 文件

system.type=2

5. 常见问题

5.1 是否添加@Configuration 注解(原因暂不明确)

  初始化其他Bean时如果依赖配置类,则配置类不能添加@Configuration注解,否则spring会提示有两个bean,必须指定一个bean;

  实例化其他Bean时如果不依赖配置类,配置类添加@Configuration注解也可以正常运行;

原文地址:https://www.cnblogs.com/virgosnail/p/10263918.html