SpringBoot+Dubbo+Shiro 导致dubbo无法注入到Realm的问题解决方案

问题的原因加载顺序引起的。

方案一:用spring-dubbo配置文件的形式, 这个注入应该没问题

主要说方案二:采用dubbo注解@Reference注入, 在实际情况中, 由于shiro和dubbo加载顺序的原因, 会导致使用@Reference的bean注入到Realm中为null, 故在其他地方可以引用 该dubbo bean, 然后转化为spring bean,再用spring上下文调用即可得到转化后的dubbo bean即可。(配置文件的形式会 先把dubbo bean转化为spring bean, 再采用@Autowired注入在加载顺序上不会和dubbo冲突, 故可以成功注入)

方法:

1. 在Controller上引用该dubbo bean

@Reference(version = "1.0.0")
IAccountService iAccountService;

@Bean(name = "iAccountService")
public IAccountService getIAccountService(){
return iAccountService;
}

 

2.添加上下文工具类

@Component
public class SpringBeanFactoryUtils implements ApplicationContextAware {
    private static ApplicationContext context = null;

    public static <T> T getBean(Class<T> type) {
            return context.getBean(type);
      }

    public static <T> T getBean(String name, Class<T> type) {
          return context.getBean(name, type);
       }
 

  @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.err.println("SpringBeanFactoryUtils be inited...");
if (SpringBeanFactoryUtils.context == null) {
SpringBeanFactoryUtils.context = applicationContext;
}
   }
}

 

 

3.在Realm中引用bean

public class MyShiroRealm extends AuthorizingRealm {

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

String userName = (String) token.getPrincipal();
IAccountService iAccountService = SpringBeanFactoryUtils.getBean("iAccountService",IAccountService.class);
Account account = iAccountService.selectAccountByLogin(userName, null);

if (account == null) {
throw new UnknownAccountException();// 用户名密码不正确
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值