spring 读取配置文件,将值注入到静态字段

resources/config/config-dev.properties

es.ip.node=xxxxxxx
cluster.name=xxxxxxx
client.transport.sniff=xxxxxxx

加载properties
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath:config/config-${env}.properties</value>
</list>
</property>
</bean>

对应属性的bean
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
* <p>Description:读取properties文件</p>
*
* @Author: Austin
**/
@Component
public class ESParams {
public static String esIpNode;
public static String clusterName;
public static String clientTransportSniff;

@Value("${es.ip.node}")
public void setEsIpNode(String esIpNode) {
ESParams.esIpNode = esIpNode;
}

@Value("${cluster.name}")
public void setClusterName(String clusterName) {
ESParams.clusterName = clusterName;
}

@Value("${client.transport.sniff}")
public void setClientTransportSniff(String clientTransportSniff) {
ESParams.clientTransportSniff = clientTransportSniff;
}
}
注意:标颜色的地方,稍有不慎就少加或者写错,另外需要将自动生成setter的方法的修饰符static去掉,否则spring无法注入

现在可以在任何类中直接使用 ESParams.xxx 即可方便引用,如 ESParams.esIpNode 了


猜你喜欢

转载自www.cnblogs.com/austinspark-jessylu/p/8962915.html