项目启动时报错找不到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();
    }
}
相关推荐
李广坤4 小时前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
爱可生开源社区1 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1771 天前
《从零搭建NestJS项目》
数据库·typescript
加号32 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏2 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐2 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
百锦再2 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
tryCbest2 天前
数据库SQL学习
数据库·sql
jnrjian2 天前
ORA-01017 查找机器名 用户名 以及library cache lock 参数含义
数据库·oracle
十月南城2 天前
数据湖技术对比——Iceberg、Hudi、Delta的表格格式与维护策略
大数据·数据库·数据仓库·hive·hadoop·spark