Spring中为static变量,代码块进行注入
问题背景
url1原本是写死的,目前需要对url1 进行参数注入,同时将url1给到静态代码块
private static String url1 = "http://url1";
private static HashMap<String,String> urls = new HashMap<>();
static {
urls.put("xxxUrl",url1);
}
解决办法
执行优先级(顺序):构造方法>@Value>@PostConstruct
使用@Value和@PostConstruct解决
@Value和非静态的set方法可以实现对静态变量url1的赋值,然后对urls这个map的操作需要在url1初始化后执行,可以采用@PostConstruct来实现
@Value("${spring.mail.host}")
private static String url1 = "http://url1";
private static HashMap<String,String> urls = new HashMap<>();
@Value("${spring.mail.host}")
public void setUrl1(String url1) {
ConTest.url1 = url1;
}
@PostConstruct
public void init(){
urls.put("xxxUrl",url1);
System.out.println(urls);
}