springboot:shiro注入dubbo服务空指针问题

问题描述

最近搭建springboot+dubbo+shiro微服务时,自定义的shiro的realm组件中:

@Component
public class AuthRealm extends AuthorizingRealm {
    @Reference
    private AccountService accountService;

调用dubbo服务accountService时,出现了空指针的异常。

问题原因

dubbo的@Reference机制,是在spring bean全部注册完成后,再注入的spring bean中。
而shiro的authRealm调用代码:

    @Autowired
    private AuthRealm authRealm;

    @Bean
    public SessionsSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(authRealm);
        return securityManager;
    }

在代码中我们可以看到,注册securityManager这个bean的时候,会将authRealm赋值给securityManager,但是此时accountService还未注入到authRealm中去,所以securityManager的authRealm属性中accountService字段为null。

解决方案

在将authRealm赋值给securityManager时,手动将accountService注入到authRealm中。

@Component
public class AuthRealm extends AuthorizingRealm {

    private AccountService accountService;
    
    @Autowired
    private DubboProperties properties;

    ...

    /**
     * 手动注入dubbo服务
     */
    public void setAccountService() {
        ReferenceConfig<AccountService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(properties.getApplication());
        referenceConfig.setRegistry(properties.getRegistry());
        referenceConfig.setInterface(AccountService.class);
        this.accountService = referenceConfig.get();
    }
}

@Configuration
public class ShiroConfig {

    @Autowired
    private AuthRealm authRealm;

    @Bean
    public SessionsSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        authRealm.setAccountService();
        securityManager.setRealm(authRealm);
        return securityManager;
    }
    ...
}

项目源码:https://github.com/ksyzz/spri…

    原文作者:十三
    原文地址: https://segmentfault.com/a/1190000017562276
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞