service和工具类(utils)获取yml中的配置(Service and utility classes (utils) get the configuration in YML)-其他
service和工具类(utils)获取yml中的配置(Service and utility classes (utils) get the configuration in 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中
@Autowiredprivate ElasticSearchConfig searchConfig;
String ab = searchConfig.clusterName;String bb = searchConfig.getClusterName();
#工具类中
注意:@Compnent必须加
@Componentpublic 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(); }
}
————————
application. The configuration in the YML file is as follows
es: #集群名 clusterName: elasticsearch
1、@Value(“${es.clusterName}”)
It is OK in controller and service, but not in tool class (utils)
2、@ConfigurationProperties
Note that the get set method is unnecessary and cannot be 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中
@Autowiredprivate ElasticSearchConfig searchConfig;
String ab = searchConfig.clusterName;String bb = searchConfig.getClusterName();
# tool class
Note: @ component must be added
@Componentpublic 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(); }
}