NutzCN Logo
问答 shiro自定义的realm没注入userService
发布于 2983天前 作者 chenhuwo 5184 次浏览 复制 上一个帖子 下一个帖子
标签:
@IocBean
public class UserRealm extends AuthorizingRealm{
	
	static final Log logging = Logs.get();
	
	@Inject
	private UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken toke) {
		UsernamePasswordToken token = (UsernamePasswordToken) toke;
		String username = token.getUsername().trim();
		char[] password = token.getPassword();
		//下面空指针
		User user = userService.getUserByUsername(username);
		
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, ByteSource.Util.bytes(user.getPassword()),ByteSource.Util.bytes(user.getSalt()), this.getName());
		
		return info;
	}
}
@IocBean
public class UserService {
	
	@Inject
	private Dao dao;
	
	public User getUserByUsername(String username){
		return dao.fetch(User.class,Cnd.where("username","=",username));
	}
}
1 回复

因为ShiroFilter比NutFilter先初始化,所以不能直接拿到的, 所标注的注解也没法生效. 但可以换个方式

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken toke) {
		UsernamePasswordToken token = (UsernamePasswordToken) toke;
		String username = token.getUsername().trim();
		char[] password = token.getPassword();
		//下面空指针
		if (userService == null)
		    userService = Mvcs.ctx().getDefaultIoc().get(UserService.class); // 取一次即可
		User user = userService.getUserByUsername(username);
		
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, ByteSource.Util.bytes(user.getPassword()),ByteSource.Util.bytes(user.getSalt()), this.getName());
		
		return info;
	}

添加回复
请先登陆
回到顶部