application.xml中(我的是spring-mybatis.xml中)
<!-- elasticsearch配置 -->
<bean id="propertyConfigurer" class="com.mlwy.elastic.util.CustomPropertyConfig">
<property name="locations">
<list>
<value>classpath*:elasticsearch.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
CustomPropertyConfig
package com.mlwy.elastic.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
/**
* 读取配置文件内容
* 20210517
* @author chenhbj
*/
public class CustomPropertyConfig extends PropertyPlaceholderConfigurer{
private static Map<String, Object> ctxPropertiesMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
ctxPropertiesMap = new HashMap<String, Object>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
}
public static Object getContextProperty(String name) {
return ctxPropertiesMap.get(name);
}
}
引用
....
(String) CustomPropertyConfig.getContextProperty("elasticsearch.nodes")
....
properties文件
#配置es节点信息,逗号分隔。 10.4.0.43:9300,172.16.30.126:9300
elasticsearch.nodes=10.4.0.43
elasticsearch.post=9200