一、static静态变量与非静态变量
如在application.properties中配置变量:
value: 127.0.0.1:8081
staticvalue: 127.0.0.1:8081
获取:
@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;
}
}
二、获取中文配置
自定义值如果是中文,获取可能会乱码。需要设置读取的编码:
spring项目:在springContext_service.xml文件中设置字符编码:
<context:property-placeholder location="classpath:config/param.properties" ignore-unresolvable="true" file-encoding="UTF-8"/>
springboot项目:首先,从配置文件读取汉字乱码的真正原因:
application.properties中文乱码是因为spring boot项目默认的加载配置文件application是
通过字符集ISO-8859-1载入的;解决方法:
1、方法1:在总application.properties文件中设置字符编码:
#设置编码
banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.messages.encoding=UTF-8
spring.freemarker.charset=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.forcr=true
spring.http.encoding.enabled=true
2、方法2:
创建一个新的properties配置文件,如:business.properties,设置文件编码格式为UTF-8,
引入配置并指定字符集,注意:这种方式针对application.properties是不行的。
然后在spring boot项目随便启动类或者需要的类上加上下面注解,获取的中文便不会乱码
@PropertySource(value = {
"classpath:business.properties"
}, encoding = "UTF-8")
3、方法3: 将application.properties改为application.yml
4、方法4:网上常说的方法如下图设置
还说前提application.properties文件编码为UTF-8,但是我试了有时候可以有时候不行,也不知道为啥;其实上述的办法就是将中文转换为Unicode码,再在idea编辑器中转换为中文。
实际存放的还是Unicode码。所以对于生产的乱码,如果用这种方法,你还不如直接把汉字
转为Unicode码放进生产的配置文件里;比如存储:星期一:
demo.day = 星期一
在线转成unicode编码
在线 Unicode 编码转换 | 菜鸟工具 (runoob.com)
则改成demo.day = \u661f\u671f\u4e00
三、获取非spring托管的配置
spring托管的Bean(使用@Compont、@Service等等spring bean的注解)类中可以使用@Value获取,非spring托管的是获取不到的,可以
1、使用Environment
Environment env = ApplicationContextProvider.getBean(Environment.class);
String property = env.getProperty("spring.application.name");
2、使用Nacos,并使用Nacos自带的获取配置的工具类