Configuration, ConfigurationProperties和EnableConfigurationProperties用法

最近刚刚解决了个错误,突然又发现这个类在spring容器中找不到,

于是我就加一个 @Component的注解,哈哈直接启动成功,那我如果吧这个注解去掉,加上一个@Configuration的注解呢,哈哈还是可以的,毕竟里面已经有这个@Component的注解了。所以我就整理下Configuration,ConfigurationProperties,EnableConfigurationProperties的作用,

 

@Configuration这个注解的主要作用是把使用该注解的类当做Bean来使用,用于配置Spring容器。 @ConfigurationProperties(prefix="xxxx") 用来获取相同父标签的元素的值。具体使用案例见下文。 **@EnableConfigurationProperties(xxx.class)**将配置好的类进行使用,在内填入参数类。

具体案例:

my:
servers:
	- dev.example.com
	- another.example.com
复制代码

如果要获取该yml文件的配置参数,我们可以通过这个方式来进行获取

@ConfigurationProperties(prefix="my")
public class Config {
 
	private List<String> servers = new ArrayList<String>();
 
	public List<String> getServers() {
		return this.servers;
	}
}
复制代码

在类中使用该注解,就能获取相关属性,该类需要有对应的gettersetter方法。 这样就相当于具备了获取yml文件中参数属性的能力,但是并不代表能用,用的时候需要注意在类上面加入@Component注解,这样Spring才能获取到相关属性。


@Component
@ConfigurationProperties(prefix="acme")
public class AcmeProperties {
 
	// ... see the preceding example
 
}

另一种使用的方法则是在需要使用这个配置类的类上方标注**@Configuration@EnableConfigurationProperties(xxx.class)**

@Configuration
@EnableConfigurationProperties(XXXProperties.class)
public class MyConfiguration {
}

 

# application.yml
acme:
	remote-address: 192.168.1.1
	security:
	    username: admin
	    roles:
	        - USER
	        - ADMIN
@Service
public class MyService {
 
	private final AcmeProperties properties;
 
	@Autowired
	public MyService(AcmeProperties properties) {
	    this.properties = properties;
	}
 
 	//...
 
	@PostConstruct
	public void openConnection() {
		Server server = new Server(this.properties.getRemoteAddress());
		// ...
	}
 
}

上面这种方法也是能用从yaml文件中读取到相对应的配置,然后再@Service层中,使用构造器的方式进行注入,这样就能调用相关属性。

引用:  https://juejin.im/post/5d13336d51882532230bce41

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值