Static fields use the @Value annotation to get the value in the configuration file

When developing with SpringBoot, we are all accustomed to using the @Value annotation to obtain the value in the configuration file and assign it to the variable. In many applications, we cannot get the value when initializing some configurations, such as some beans in spring, which can be used at this time. static properties,

That is: define the parameter variable modified by static to obtain the value assigned in the configuration file through the @Value annotation ;

1. Define properties and values ​​in the configuration file

server.ip=192.158.1.123
server.port=8888

2. Declare static properties in the class Use @Value to get the value of the configuration file and assign it to the declared static variable

private static String serverIp;
private static String serverPort;

@Value("${server.ip}")
public void setServerIp(String serverIp){
  this.serverIp = serverIp;
}

@Value("${server.port}")
public void setServerPort(String serverPort){
  this.serverPort= serverPort;
}

Well, the use of @Value to obtain the value in the configuration file and assign it to the static variable has been completed. If it is a general variable to obtain the value in the configuration file, the variable declared in the above process can be achieved without the static modifier.

 Note: Setter methods of static variables need to remove the static modifier.

Guess you like

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