問題描述:
最近嘗試SpringBoot整合Shiro,自定義的Realm中查詢用戶信息時一直報空指針異常;
單獨測試了一遍service層(查詢並封裝到User對象中)是沒有問題的;
項目描述:
SpringBoot項目,簡單分成Entity/Service/Mapper/Controller層;
項目用到的ORM框架是Mybatis;
Realm如下
@Autowired
private TestServiceImpl testService;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String principle = (String) token.getPrincipal();
UserLogin userLogin = new UserLogin();
System.out.println(testService);
// 就下面介行一直報空指針
userLogin = testService.selectUserLoginByUsername(principle);
if (userLogin == null) {
return null;
}
String password = userLogin.getPassword();
// 密碼md5加密過了
String salt = userLogin.getSalt();
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principle, password, ByteSource.Util.bytes(salt), this.getName());
return simpleAuthenticationInfo;
}
上述代碼在執行完 查詢那行 後就報空指針的錯誤。
起初以爲是sql的問題或者是查詢的結果集映射不對。但是其實不是,因爲如果是Mapper.xml的問題,應該在userLogin.getXXX()取值的時候才報空指針,於時想到應該是testService對象爲null,也就是說**@Autowired注入失敗**了。
測試類如下
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private TestServiceImpl testService;
@Test
public void Test() {
// 創建UserRealm對象實例,注意這行
UserRealm userRealm = new UserRealm();
DefaultSecurityManager securityManager = new DefaultSecurityManager();
securityManager.setRealm(userRealm);
// md5加密
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashIterations(1);
hashedCredentialsMatcher.setHashAlgorithmName("md5");
userRealm.setCredentialsMatcher(hashedCredentialsMatcher);
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("root", "666666");
try {
subject.login(token);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("是否認證通過:" + subject.isAuthenticated());
subject.logout();
System.out.println("是否認證通過:" + subject.isAuthenticated());
}
}
測試類中我們是通過new的方式創建的UserRealm對象實例,所以它並沒有受到Spring的管理,Spring容器中都沒有的實例怎麼注入呢?所以造成了上述的空指針異常。
解決辦法:
UserRealm userRealm = new UserRealm();
替換成
@Autowired
private UserRealm userRealm;