springBoot配置类的使用技巧

我们可以在配置中心application.yml中配置自定义的参数选项.
我们的需求是在程序运行的时候将集群的列表加载到代码中.
在application.yml中配置

zk.
	lists:[a,b,c]

创建bean

@Data
@Component  //这样只是将该组建注册进容器
@ConfigurationProperties(prefix="cluster")
public class Cluster{
    
    
	private List<String> lists;
}

我们想在项目中某个组件 A 加载进去后立即加载ConcurrentHashMap中

@Component
public class A{
    
    
	private static ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
	@AutoWired
	private Cluster cluster;

	@PostConstruct //在组建加载进容器后自动调用
	public void init(){
    
    
		for(String  msg: cluster.getLists()){
    
    
			String name = get(msg);//通过自定的get方法获取到指定的值
			map.put(msg,name);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_43079376/article/details/108254160