dubbo配置的filter,中注入 spring bean 为 null
解决:spring-dao的注入顺序要在dobbo filter之前
dubbo Filter中注入Spring 的Bean 三种方式:
方式一:dubbo通过setter方式自动注入
private TestService testService;
public void setTestService(TestService testService) {
this.testService = testService;
}
方式二:通过ApplicationContext的方式来获取
可以自己先实现一个SpringUtil实现ApplicationContextAware接口,如下
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
// 获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// 通过name获取 Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
}
然后调用这个工具类来获取对象
TestService testService = (TestService) SpringUtil.getBean("testService");
方式三:使用ServiceBean
@Autowired
private ICallerRepository callerRepository;
...
//用dubbo提供的ServiceBean即可获取bean,因为该类已经实现了ApplicationContextAware
ApplicationContext context= ServiceBean.getSpringContext();
callerRepository = context.getBean(ICallerRepository.class);
**setter源码分析:**如何在filter等dubbo自管理组件中注入spring的bean - 简书