springboot③整合shiro, @Autowired失效

springboot在集成shiro的时候,要编写realm。错误实例:

/*	//有可能是注入失败的
	@Autowired
	UserDao userMapper;
	@Autowired
	MenuService menuService;*/

	/**
	 * 授权
	 * @param arg0
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {

		UserDO userDO = (UserDO)SecurityUtils.getSubject().getPrincipal();
		Long userId =  userDO.getUserId();
		MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
		Set<String> perms = menuService.listPerms(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		return info;
	}

使用@Autowired注入用户dao有可能失败,是因为Shiro框架初始化比Spring框架的某些部件早,导致使用@Autowire注入Shiro框架的某些类还没有被Spring正确初始化。

解决办法:

使用ApplicationContextRegister.getBean()方法,手动获取需要的注入的类,如下代码:

/**
* 认证
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
   String username = (String) token.getPrincipal();
   Map<String, Object> map = new HashMap<>(16);
   map.put("username", username);
   String password = new String((char[]) token.getCredentials());

  UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
   // 查询用户信息
   UserDO user = userMapper.list(map).get(0);
   // 账号不存在
   if (user == null) {
      throw new UnknownAccountException("账号或密码不正确");
   }
   // 密码错误
   if (!password.equals(user.getPassword())) {
      throw new IncorrectCredentialsException("账号或密码不正确");
   }
   // 账号锁定
   if (user.getStatus() == 0) {
      throw new LockedAccountException("账号已被锁定,请联系管理员");
   }
   SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
   return info;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值