使用static声明的变量是不能被@Value附上值的,像这样:
@Value("${md.appKey}")
private static String appKey;
但是有的时候为了配置的统一管理,必须要把配置放到配置文件里面统一配置,这个时候要怎么办呢?
方法一
在 .yml或者 .properties文件里面加入你想要的配置,这是必须的,不多说。
1、首先需要在你的类上加上@component注解
@Component
public class RestTemplateUtil {}
2、然后给静态变量生成set方法,在set方法上面进行赋值:
private static String appKey;
private static String secretKey;
private static String requestUrl;
@Value("${md.appKey}")
public void setAppKey(String appKey) {
RestTemplateUtil.appKey = appKey;
}
@Value("${md.secretKey}")
public void setSecretKey(String secretKey) {
RestTemplateUtil.secretKey = secretKey;
}
@Value("${md.requestUrl}")
public void setRequestUrl(String requestUrl) {
RestTemplateUtil.requestUrl = requestUrl;
}
这样就可以成功的给静态变量成功的附上值了。
注意!set方法不能有static关键字
有的小伙伴直接用编辑器自动生成set方法,编辑器会自动生成static的set方法,那样也是不能赋值成功的。
方法二(比较繁琐,可以不看)
@Component
public class RestTemplateUtil{
@Autowired
public PropertiesUtil propertiesUtil;
private static String appKey;
@PostConstruct
public void init (){
appKey = propertiesUtil.getIoAppKey();
}
}
首先,一定要在类上加上@Component注解,把该类注册到spring容器中。这是知识点,要考的。
@Component
public class RestTemplateUtil{}
然后就是PropertiesUtil这个类,我们用一个类来统一管理配置文件注入,用的就是这个,在类里面我是这样写的:
@Value("${md.appKey}")
private String ioAppKey;
项目启动时,所有的配置文件都已经注入到这个类里面去了,取得话用get方法取就行了
我先是定义了一个静态变量
private static String appKey;
然后又进行了一步操作,把配置工具类里面的值赋给静态变量
@PostConstruct
public void init () {
appKey = propertiesUtil.getIoAppKey();
}
这其中用到了@PostConstruct
关于该注解的具体细节,我还需要着重看一下,
目前只知道方法用了这个注解之后,该方法会在依赖关系注入完成之后执行。
综上,就可以完成配置文件对静态变量的赋值了。