springboot: shiro injecting dubbo service null pointer

Problem description When the springboot+dubbo+shiro microservice is set up recently, in the custom shiro's realm component: @Component public cla...
Problem description
Problem reason
Solution

Problem description

When the springboot+dubbo+shiro microservice is set up recently, in the custom shiro's realm component:

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

A null pointer exception occurred while calling dubbo service accountService.

Problem reason

dubbo's @ Reference mechanism is injected into spring beans after all the spring beans are registered.
shiro's authRealm call code:

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

In the code, we can see that when registering the security manager bean, the authRealm will be assigned to the security manager, but the accountService has not yet been injected into the authRealm, so the accountService field in the authRealm property of the security manager is null.

Solution

When assigning authRealm to security manager, manually inject accountService into authRealm.

@Component public class AuthRealm extends AuthorizingRealm { private AccountService accountService; @Autowired private DubboProperties properties; ... /** * Manual injection of dubbo service */ 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; } ... }

Project source code: https://github.com/ksyzz/spri...

3 December 2019, 14:52 | Views: 6593

Add new comment

For adding a comment, please log in
or create account

0 comments