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,配置类2.class})

@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 文件中,系统自动读取该文件,所以不必指定配置文件;

  prefix 表示参数 key 的前缀;

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

@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注解也可以正常运行;

猜你喜欢

转载自www.cnblogs.com/virgosnail/p/10263918.html