最近做項目用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);
}