问题描述
最近搭建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;
}
...
}