alibaba / spring-context-support

An internal support project for spring-context in Alibaba
Apache License 2.0
150 stars 83 forks source link

在方法上使用@NacosValue注解时,注入报空指针 #57

Open YanAnHuaZai opened 1 year ago

YanAnHuaZai commented 1 year ago

版本信息:

触发方式:

在方法上使用@NacosValue

private String value;

@NacosValue(value = "${nacos.test.value:default_value}",autoRefreshed = true)
void setValue(String value) {
    this.value = value;
    System.out.println("nacos测试刷新数据:" + value);
}

报错位置:

com.alibaba.spring.beans.factory.annotation.AbstractAnnotationBeanPostProcessor.AnnotatedMethodElement#inject

报错信息:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dubboServiceImpl': Injection of @NacosValue dependencies is failed; nested exception is java.lang.NullPointerException

报错原因:

变量pd为null,没有判空直接使用导致空指针

解决方案

判断如果pd为null则从member中获取 Class<?> injectedType = null != pd?pd.getPropertyType():((Method) this.member).getParameterTypes()[0];

完整方法

@Override
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {

    Class<?> injectedType = pd?pd.getPropertyType():((Method) this.member).getParameterTypes()[0];

    Object injectedObject = getInjectedObject(attributes, bean, beanName, injectedType, this);

    ReflectionUtils.makeAccessible(method);

    method.invoke(bean, injectedObject);

}