service和工具类(utils)获取yml中的配置
作者:互联网
application.yml文件中配置如下
es:
#集群名
clusterName: elasticsearch
1、@Value("${es.clusterName}")
在controller、service里可以,在工具类中(Utils)不行
2、@ConfigurationProperties
注意 get set 方法不需要,且不能是static
@Component
@ConfigurationProperties(prefix = "es")
public class ElasticSearchConfig
{
/** 集群名 */
public String clusterName;
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getApplicationName() {
return applicationName;
}
}
#service中
@Autowired
private ElasticSearchConfig searchConfig;
String ab = searchConfig.clusterName;
String bb = searchConfig.getClusterName();
#工具类中
注意:@Compnent必须加
@Component
public class ClientUtil {
private static ElasticSearchConfig searchConfig;
@Autowired
public void setSearchConfig(ElasticSearchConfig searchConfig){
ClientUtil.searchConfig = searchConfig;
}
public static void test() {
String cc = searchConfig.clusterName;
String dd = searchConfig.getClusterName();
}
}
标签:ElasticSearchConfig,String,service,clusterName,utils,public,searchConfig,static, 来源: https://www.cnblogs.com/xlj227/p/16267018.html