@RefreshScope 标记的类中属性注入值为null
说一句,国内写文章的解答的,ctrl cv好用不
我这个问题百度了一个小时没解决,外网几秒钟,真尼玛服了,抄抄抄,抄尼玛呢
下面是我出问题的代码
/**
* @Author TomShiDi
* @Since 2020/7/8
* @Version 1.0
*/
@RestController
@RequestMapping("/config")
@RefreshScope
@Slf4j
public class ConfigClientController {
@Value("${config.info}")
private String configInfo;//这里会为null
@Autowired
private ValueComponent valueComponent;//这里也是null
@GetMapping("/configInfo")
private String getConfigInfo() {
log.info("********valueComponent: {}", valueComponent.getConfigInfo());
return configInfo;
}
public void setConfigInfo(String configInfo) {
this.configInfo = configInfo;
}
}
这个注解的proxyMode默认值是ScopedProxyMode.TARGET_CLASS,这个代理
模式使用的是CGLIB方式。如果@RefreshScope使用在@Controller(不止这一个)标记的类上就会出现注入null值的问题。@RefreshScope只要是用在其他会被spring使用CGLIB代理的类上就会出问题。原因是@RefreshScope默认使用CGLIB代理,而目标类又是被CGLIB代理过的,这样就被代理了两次,第二次也就是@RefreshScope代理的时候会出现属性丢失的问题。
能知道这个问题也算巧合,之前做过基于springboot架构的代码跟踪小demo,
可以在我之前的文章中找到,在那时就考虑过使用CGLIB的方式实现,然后就出现了这个重复代理属性丢失的问题,后面花了一天改用了重写registration的方式才完成。
解决办法
切换proxyMode模式
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)