Springboot 注解之 @EnableConfigurationProperties + @ConfigurationProperties 配合使用

@ConfigurationProperties 注解的作用: 将 .properties 配置文件与对应的 Java bean 进行绑定

@EnableConfigurationProperties 注解的作用: 使 @ConfigurationProperties 注解生效,并且将组件加入 IOC 容器中

1、application.properties

Springboot 启动时默认是加载 application.properties 配置文件的,假设该配置文件中内容如下

local.host=127.0.0.1
local.port=8080

2、Java bean

// application.properties 中以 local 开头的配置与 Local 实体类进行绑定
@ConfigurationProperties(prefix = "local")
public class Local {
    private String host;
    private String port;
	... 省略 get / set / toString 方法
}	

3、测试类

使用 @EnableConfigurationProperties 注解使 Local 类上的 @ConfigurationProperties 注解生效

@SpringBootApplication
// 1、使 @ConfigurationProperties 生效
// 2、将 Local 组件加入 IOC 容器中
// @EnableConfigurationProperties 注解只要能加入到 IOC 容器中,不一定要在启动类上
@EnableConfigurationProperties(Local.class)
public class Springboot01Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext ioc = SpringApplication.run(Springboot01Application.class, args);
        Local local = ioc.getBean(Local.class);
        System.out.println(local);
    }
}

4、测试结果

原文地址:https://www.cnblogs.com/xiaomaomao/p/14268152.html