在spring-boot中,

1、如果@ConfigurationProperties所注的类可以被springboot扫描并添加进容器中作为bean(比如使用@Component等注解,或者配置扫描该类所在包等手段),那么spring容器会自动使该类上的@ConfigurationProperties生效,创建一个该类的实例,然后把对应配置属性绑定进该实例,再把该实例作为bean添加进spring容器。

下面的代码 application.properties 中配置的参数是可以注入进去的

imooc.security.browser.loginType = REDIRECT

@Component
@ConfigurationProperties(prefix = "imooc.security")
public class SecurityProperties {
private BrowserProperties browser = new BrowserProperties();
// getter and setter ....
}
public class BrowserProperties {
private LoginType loginType = "json";
// getter and setter ....
}

2、如果该类只使用了@ConfigurationProperties注解,然后该类没有在扫描路径下或者没有使用@Component等注解,导致无法被扫描为bean,那么就必须在配置类上使用@EnableConfigurationProperties注解去指定这个类,这个时候就会让该类上的@ConfigurationProperties生效,然后作为bean添加进spring容器中

@ConfigurationProperties(prefix = "imooc.security")
public class SecurityProperties {
private BrowserProperties browser = new BrowserProperties();
// getter and setter ....
}
public class BrowserProperties {
private LoginType loginType = "json";
// getter and setter ....
}

@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityCoreConfig {
// 还需要此类方能让 SecurityProperties 注入配置文件中的值
}

3.在javaconfig中@ConfigurationProperties与@Bean一起用,也是把配置文件中的属性注入该@Bean对应的要添加到容器中的bean实例中。​