最近做项目用SpringBoot+Dubbo+Shiro做项目框架,在调试shiro自定义Realm权限的时候发现,@Reference注入的dubboService为null;网上查了好多,但都没有完美解决问题,问题的原因是shirofilter加载顺序引起的。
解决问题的方法为:将dubbo bean转为spring bean,再用spring上下(ApplicationContext)转为dubbo bean 就可以了。
spring上下文转换工具:
package com.test.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringBeanFactoryUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
public static <T> T getBean(String name, Class<T> type) {
return context.getBean(name, type);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringBeanFactoryUtil.context == null) {
SpringBeanFactoryUtil.context = applicationContext;
}
}
}
将dubbo bean转为spring bean。先用@Reference引入,再用@Bean转换
package com.test.security.util;
import com.alibaba.dubbo.config.annotation.Reference;
import com.dubbo.service.sys.SysUserDubboService;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class BeanFactoryUtil {
@Reference
SysUserDubboService sysUserDubboService;
@Bean(name = "sysUserDubboService")
public SysUserDubboService getSysUserDubboService() {
return sysUserDubboService;
}
}
最后是在Realm中调用。
//定义一个dubboservice
private SysUserDubboService sysUserDubboService;
调用。
//在用dubbboservice的方法调用
if (this.sysUserDubboService == null) {
this.sysUserDubboService = SpringBeanFactoryUtil.getBean("sysUserDubboService",SysUserDubboService.class);
}