Configuration, ConfigurationProperties和EnableConfigurationProperties用法

4,846 阅读2分钟

因为之前一直对这些长得很像的注解一知半解常常因为觉得肯定是不管什么错肯定是作者的坑(自己的锅)。于是最近花了点时间去研究下具体使用方法,避免日后出错。之前用的时候也经常去看csdn上的文章,基本都是千篇一律互相抄,至于是不是对的也没人去指正。于是自己就写下自己的感受。

@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层中,使用构造器的方式进行诸如,这样就能调用相关属性。个人写的很烂,具体有问题请在评论下指出即可。