static静态变量与非静态变量获取配置文件application中变量值的区别
程序员文章站
2024-02-21 15:14:22
...
static静态变量与非静态变量获取配置文件application中变量值的区别
在spring boot项目配置文件application.yml或者application.properties中添加两个变量并赋值
value: 127.0.0.1:8081
staticvalue: 127.0.0.1:8081
在controller文件中通过@value注解获取配置文件中变量值,并赋值于普通变量
package com.example.jpahappy.Controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/getvalue")
public class getvalue {
@Value("${value}")
private String value;
@RequestMapping(method = RequestMethod.GET,value="/getvalue")
public String getvalue(){
return "this:"+value;
}
}
在浏览器中调用getvalue方法,获得结果value值读取到配置文件中赋予变量值
同样的方法,controller类中读取配置文件中变量,赋值于静态变量,静态变量与非静态变量赋值与获取方法相同
package com.example.jpahappy.Controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/getvalue")
public class getvalue {
@Value("${value}")
private String value;
@Value("${staticvalue}")
private static String staticvalue;
@RequestMapping(method = RequestMethod.GET,value="/getvalue")
public String getvalue(){
return "this:"+value;
}
@RequestMapping(method = RequestMethod.GET,value="/getstaticvalue")
public static String getstaticvalue(){
return "this:"+staticvalue;
}
}
浏览器中通过getstaticvalue方法却未能成功将配置文件中变量值赋值于静态变量,静态变量staticvalue值为null
既然如此,对静态变量赋值进行如下修改
@RestController
@RequestMapping("/getvalue")
public class getvalue {
@Value("${value}")
private String value;
private static String staticvalue;
@Value("${staticvalue}")
public void setStaticvalue(String staticvalue){
this.staticvalue = staticvalue;
}
@RequestMapping(method = RequestMethod.GET,value="/getvalue")
public String getvalue1(){
return "this:"+value;
}
@RequestMapping(method = RequestMethod.GET,value="/getstaticvalue")
public static String getvalue2(){
return "this:"+staticvalue;
}
}
先定义静态变量,通过setStaticvalue方法与@value注解成功实现将配置文件中变量赋值于静态变量