關於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();// 用戶名密碼不正確
  }

。。。。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM