Spring Dubbo @reference注解报空指针原因及处理办法

如果使用过Spring + Dubbo会发现bean装配有三种方式

Spring的 @Autowired和@Resource

Dubbo的 @Reference

有时候有些场景三个随便用都可以,但有时候会报空指针问题,特别是@Reference

1.场景

controller层@Reference 装配bean对象

spring-consumer.xml

2.项目结构:

如果项目结构如上图示例,且spring-mvc.xml为引入spring-consumer.xml文件

3.报错类型

@Reference 装配bean对象空指针,无法调用远程服务

4.原因

程序启动时读取spring-*.xml配置文件,会初始化一个xmlwebapplicationcontext也就是应用的rootContext顶级容器,这个容器在serverletcontext上下文中,然后dispatcherservlet开始初始化,并初始化了controller类,同时将dubbo注解reference的实例set给了controller;

但是接着servlet初始化过程中又再一次读取了spring-mvc.xml配置文件,同时也对controller进行了初始化,但是与顶级容器初始化不同的是,reference实例化的过程没有进行,因此在mvc容器中的controller是没有注入reference标注的实例的,因此出现NULL的情况。

这方面可以参考下面博客博主分析很详细

https://blog.csdn.net/zhou_java_hui/article/details/53039491

5.解决办法

5.1将spring-consumer.xml引入spring-mvc.xml文件;

5.2使用注解@autowired或者 @resource 不用@Reference;

5.3spring-consumer.xml 文件最后加入扫描全项目;

<!--注解扫描 -->
<dubbo:annotation package="com.tn.open" /> 

猜你喜欢

转载自blog.csdn.net/qq_39575279/article/details/83546401