@ConfigurationProperties 与 @EnableConfigurationProperties

在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实例中。

原文:https://blog.csdn.net/qq_36951116/article/details/82927426
推荐:https://blog.csdn.net/andy_zhang2007/article/details/78761651

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值