網(wǎng)上找了一堆介紹,越說越糊涂,后面自己測(cè)試后明白了.
先上代碼
- 注入配置值方法1: @value
@RefreshScope
@Configuration
public class ScopeTestConfig {
@Value("config.test.one")
public String one;
@Value("config.test.two")
private String two;
public String getOne() {
return one;
}
public String getTwo() {
return two;
}
}
- 注入配置值方法2: @ConfigurationProperties(prefix = "config.test")
@RefreshScope
@Configuration
@ConfigurationProperties(prefix = "config.test")
public class ScopeTestConfig1 {
public String one;
private String two;
public String getOne() {
return one;
}
public String getTwo() {
return two;
}
}
- 取值方式1: 通過注入bean的field獲取值
@Autowired
ScopeTestConfig config;
void test(){
String fieldVal1 = config.one;
}
- 取值方式2: 通過注入bean的方法間接讀取field獲取值
@Autowired
ScopeTestConfig config;
void test(){
String getMethod1 = config.getOne();
String getMethod2 = config.getTwo();
}
-
取值清單(2種方式情況一樣)
| 取值方式 | 無@RefreshScope | 有@RefreshScope |
|---|---|---|
| 方式1(field取值) | 有值 | null |
| 方式2(方法取值) | 有值 | 有值 |
-
總結(jié)陳詞
@RefreshScope 會(huì)使注入的值放到代理類中,
而當(dāng)前bean的屬性字段是沒有值的,直接讀取bean的field會(huì)為null,
只有通過方法(不一定是get方法)才會(huì)觸發(fā)去代理類中取值.
很多遇到在@Controller中直接@Value獲取不到值,解決方法是定義另外一個(gè)配置類,再取值就可以了,其實(shí)忽略了取值的方式, 都是代理惹的禍.