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

发布了75 篇原创文章 · 获赞 3 · 访问量 1975

猜你喜欢

转载自blog.csdn.net/qq_32565267/article/details/104376782