关于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();// 用户名密码不正确
  }

。。。。。。

posted @ 2018-09-19 11:19  水冰刺  阅读(2273)  评论(1编辑  收藏  举报