springcloud-@RefreshScope注解

一.问题

  1. 注入过后不调用方法获取不到对应的value值

二.演示

 @Component
@RefreshScope
public class Val {
@Value("${schedule.detectAlarmCron}")
public String detectAlarmCron;
}

获取类

 @SpringBootTest
public class Case {

@Autowired
private Val val3;

@Test
public void case2() throws UnsupportedEncodingException, ParseException {
System.out.println(val3.detectAlarmCron);
}

输出

 null 

三.原因及解决办法

原因

  1. 初步猜测原因,在注入bean时未给成员变量赋值,堆内存中的值一直为null(因为注入的对象是代理出来的),当方法栈内存需要值的时候,从远程的配置中心中取(代理),引用地址是个获取途径,以此保证实时性。
  2. 初步猜测已经得到了验证,引用自他人博客:点击跳转至该博客
 这个注解的proxyMode默认值是ScopedProxyMode.TARGET_CLASS,这个代理

模式使用的是CGLIB方式。如果@RefreshScope使用在@Controller(不止这一个)标记的类上就会出现注入null值的问题。@RefreshScope只要是用在其他会被spring使用CGLIB代理的类上就会出问题。原因是@RefreshScope默认使用CGLIB代理,而目标类又是被CGLIB代理过的,这样就被代理了两次,第二次也就是@RefreshScope代理的时候会出现属性丢失的问题。

解决

  1. 通过get方法取成员变量值
  2. @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)

标签: Java

添加新评论