项目启动时报错找不到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();
    }
}
相关推荐
倔强的石头_14 小时前
《Kingbase护城河》——猎捕慢查询:执行计划的微观解析与索引调优实战
数据库
SelectDB16 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
jiayou642 天前
KingbaseES 表级与列级加密完全指南
数据库·后端
GBASE3 天前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
xiezhr3 天前
逛GitHub发现了一款免费的带AI功能的数据库管理工具
数据库·ai编程·dba
吃糖的小孩4 天前
给 QQ AI 机器人设计“可控记忆”:会话摘要、手动长期记忆与角色卡边界
数据库
笃行3505 天前
金仓数据库数据安全双防线:静态存储加密与传输加密实战
数据库
笃行3505 天前
金仓数据库物理备份实战:sys_rman 全流程演练与误覆盖抢救
数据库
笃行3505 天前
金仓数据库逻辑备份实战:从全库导出到 Schema 替换的完整闭环
数据库