Spring reads configuration files and injects values into static fields

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;
}
}
Note: In the place where the color is marked, add less or write it wrong if you are not careful. In addition, you need to remove the static modifier of the method that automatically generates the setter , otherwise spring cannot inject 

it. Now you can use ESParams.xxx directly in any class for convenience. References, such as ESParams.esIpNode


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324980571&siteId=291194637