项目启动时报错找不到UserDetailsService

前言

项目启动时报错找不到UserDetailsService

Description:

Field userDetailsService in com.haixin.initframework.config.SecurityConfig required a bean of type 'org.springframework.security.core.userdetails.UserDetailsService' that could not be found.

The injection point has the following annotations:

通过学习记录这个问题,笔者发现自己对security这块还是比较欠缺。确实在之前的学习开发中没有系统的学习过这一块,后面还是要对这块系统学习一下。


项目启动时报错找不到UserDetailsService问题原因,解决方案

  • 前言
  • [1 具体问题](#1 具体问题)
  • [2 问题原因](#2 问题原因)
  • [3 解决方案](#3 解决方案)

1 具体问题

java 复制代码
Description:

Field userDetailsService in com.haixin.initframework.config.SecurityConfig required a bean of type 'org.springframework.security.core.userdetails.UserDetailsService' that could not be found.

The injection point has the following annotations:

2 问题原因

错误信息提示,系统在创建com.haixin.initframework.config.SecurityConfig时,里面所需要的org.springframework.security.core.userdetails.UserDetailsService没有被找到。

3 解决方案

UserDetailsService是Spring Security中用于加载用户信息(如用户密码,角色,用户名等)的接口,通常用于身份认证,通过用户的身份信息与数据库中的记录进行匹配。

需要在项目中创建UserDetailsService的实现类。

如下大致代码:

java 复制代码
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 假设这是从数据库查询到的用户信息
        if (!"admin".equals(username)) {
            throw new UsernameNotFoundException("用户不存在:" + username);
        }

        // 创建一个用户,包含用户名、密码和权限信息
        return User.withUsername("admin")
                   .password("{noop}password")  // {noop} 表示不加密,仅供测试
                   .roles("USER")
                   .build();
    }
}
相关推荐
Lethehong7 小时前
Oracle 加个字段,目标库就报错?KFS 用“先拆后组“打通异构 DDL
数据库·oracle
Web极客码7 小时前
锁定真正的磁盘卡顿:我用 OpenCode 配合 eBPF 诊断 NVMe 队列深度延迟与 I/O 写放大
数据库·oracle
cspttty8 小时前
2027用户研究求职准备:应用统计学如何补齐研究设计与业务表达
大数据·数据库
roman_日积跬步-终至千里9 小时前
【数据Agent论文·查询与语义|05】Spider:为什么换一个数据库,模型就不会查了?
数据库·数据分析
猫咪很可爱9 小时前
Oracle RAC 启动失败排查:私网通信与内核参数优化实战
运维·数据库·oracle
XLYcmy10 小时前
《数字经济赋能城市低碳治理的路径研究检索报告》审阅与修改指导意见——基于完整检索报告体例的完整性诊断、学术规范核查与方法论纠偏 上
数据库·ai·chatgpt·文心一言·检索·知网·豆包
泡海椒10 小时前
JQuick-SQL 快速开始:注册内存表并执行查询
数据库·windows·sql
ss27310 小时前
PG实战笔记 | 09 PostgreSQL psql客户端基本操作
数据库·笔记·postgresql
电商API_1800790524710 小时前
反向海淘多币种结算:汇率该在哪个时点被冻结
java·开发语言·数据库·跨境电商·1688 api
搞AI的金鱼11 小时前
skill agent workflow的区别
数据库