security UserDetailsService.java如何配置 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 涉及com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
时间: 2023-06-24 13:09:07 浏览: 68
在使用 Spring Security 进行身份认证时,我们通常需要自定义一个实现了 `UserDetailsService` 接口的类来获取用户信息。该接口中的方法 `loadUserByUsername(String username)` 用于根据用户名获取用户信息并返回一个 `UserDetails` 对象。
在 `loadUserByUsername(String username)` 方法中,我们可以通过 MyBatis-Plus 提供的 `QueryWrapper` 来构建一个查询条件,以查询数据库中的用户信息。例如:
```java
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 构建查询条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username", username);
// 查询用户信息
User user = userMapper.selectOne(queryWrapper);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
// 封装用户信息并返回
return new User(user.getUsername(), user.getPassword(), Collections.emptyList());
}
}
```
在上述代码中,我们首先通过 `QueryWrapper` 构建了一个查询条件,然后通过 `userMapper.selectOne(queryWrapper)` 方法查询数据库中的用户信息。最后,我们将查询到的用户信息封装成一个 `UserDetails` 对象并返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)