Skip to content

配置文件注入

@ConfigurationProperties

@ConfigurationPropertiesSpring / Spring Boot 用来把配置文件中的属性批量绑定到 Java 对象上的注解。它常用于读取 application.ymlapplication.properties 中的一组配置。

yaml
user:
  name: zhangsan
  age: 18
  address: beijing

配置文件需要有getter和setter

java
@Component
@ConfigurationProperties(prefix = "user")
public class UserProperties {

    private String name;
    private Integer age;
    private String address;

    // getter setter
}

@ConfigurationProperties 本身 不会创建 Bean

java
@Component
@ConfigurationProperties(prefix = "user")

@EnableConfigurationProperties

有些第三方配置类并没有被Spring容器管理,我们也不可能修改他人的源代码。我们可以使用@EnableConfigurationProperties

例如:

java
@ConfigurationProperties(prefix = "user")
public class UserProperties {

    private String name;
    private Integer age;

}

这个类:

  • 没有 @Component
  • 没有 @Bean

Spring 不会创建它。

这时候就需要:

java
@EnableConfigurationProperties(UserProperties.class)