Spring reads a configuration file, injecting values into a static field

Source: Internet
Author: User

Resources/config/config-dev.properties

Es.ip.node=xxxxxxx
Cluster.name=xxxxxxx
Client.transport.sniff=xxxxxxx

Load 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>

The bean that corresponds to the attribute
Import Org.springframework.beans.factory.annotation.Value;
Import org.springframework.stereotype.Component;

/**
* <p>description: Read properties file </p>
*
* @Author: Austin
**/
@Component
public class Esparams {
Public StaticString Esipnode;
Public StaticString clustername;
Public StaticString 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: The color of the place, a little bit less error or write wrong, in addition to the automatic setter method to remove the modifier static  , otherwise spring cannot inject

You can now use esparams.xxx directly in any class for easy reference, such as Esparams.esipnode.


Spring reads a configuration file, injecting values into a static field

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.