
在学 dubbo,想用注解,然后消费方一直报空指针,我先声明没加入 SpringMVC 或者 boot 导致加载顺序出错,我就是纯 spring 下写 demo 学习,贴一下我的配置和代码,求大佬指点问题所在
提供方 xml
<!-- 加入 spring 注解扫描 --> <context:component-scan base-package="com.hanting"/> <!--计算依赖关系--> <dubbo:application name="provider"/> <!--使用 zookeeper 注册中心暴露服务--> <dubbo:registry address="zookeeper://localhost:2181"/> <!-- 用 dubbo 协议在 20880 端口暴露服务 --> <dubbo:protocol name="dubbo" port="20880"/> <!-- 使用注解方式暴露接口 --> <dubbo:annotation package="com.hanting"/> <!-- 接口--> <dubbo:service interface="com.hanting.service.UserService" ref="userService" /> 提供方 impl
import com.alibaba.dubbo.config.annotation.Service; import com.hanting.service.UserService; import org.springframework.stereotype.Component; @Component("userService") @Service() public class UserServiceImpl implements UserService { ... } 消费方 xml
<dubbo:application name="consumer"/> <!--向 zookeeper 订阅 provider 的地址,由 zookeeper 定时推送--> <dubbo:registry address="zookeeper://localhost:2181"/> <!--使用 dubbo 协议调用定义好的 api.PermissionService 接口--> <dubbo:reference id="userService" interface="com.hanting.service.UserService"/> <!-- 使用注解方式暴露接口 --> <dubbo:annotation package="com.hanting"/> <!-- 加入 spring 注解扫描 --> <context:component-scan base-package="com.hanting"/> 消费方测试
import com.alibaba.dubbo.config.annotation.Reference; import com.hanting.service.UserService; import org.springframework.stereotype.Component; @Component public class UserTest { @Reference private UserService userService; public void test() { userService.addUser("aaa"); } } 消费方的 console
consumer start... Exception in thread "main" java.lang.NullPointerException at com.hanting.controller.UserTest.test(UserTest.java:25) at Consumer.main(Consumer.java:19) 1 yidinghe Nov 5, 2017 |
2 bxb100 Nov 5, 2017 没用过 Dubbo, 难道 Spring DI 注入不是提供实现类吗 |
3 lishunli Nov 6, 2017 提供方删除 <context:component-scan base-package="com.hanting"/> <dubbo:service interface="com.hanting.service.UserService" ref="userService" /> 消费方删除 <dubbo:reference id="userService" interface="com.hanting.service.UserService"/> <context:component-scan base-package="com.hanting"/> dubbo:annotation 就已经包含了上面的,再试试 |
4 xiaofdejimo OP @lishunli 这个后来我也反应过来了,我的问题我想明白了,是我调用这个消费者的时候是直接 new 出来调用的,不是通过 springIOC 给我的,所以就无法扫描到注解,是我 spring 这儿没想明白 |