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; } ... }
相关推荐
nullcy 2020-04-25
visionzheng 2020-04-14
ganjing 2020-02-16
杜鲁门 2020-11-05
luckyxl0 2020-08-16
Dullonjiang 2020-08-09
xclxcl 2020-08-03
zmzmmf 2020-08-03
MicroBoy 2020-08-02
ganjing 2020-08-02
likesyour 2020-08-01
zmzmmf 2020-07-09
MicroBoy 2020-07-05
zzhao 2020-06-26
子云 2020-06-18
visionzheng 2020-06-07
neweastsun 2020-06-04
ErixHao 2020-06-03
GDreams0 2020-06-01