问题描述:
最近尝试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;