项目启动时报错找不到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();
    }
}
相关推荐
郝学胜-神的一滴3 分钟前
系统设计 012:从用户系统出发,吃透缓存、数据库与高并发设计
java·数据库·python·缓存·php·软件构建
米高梅狮子3 分钟前
01.ELK企业日志分析系统
运维·服务器·网络·数据库·elk·oracle
小杍随笔6 分钟前
【redb vs SQLite (rusqlite) 技术选型对比】
数据库·sqlite
暗夜猎手-大魔王7 分钟前
转载--AI Agent 架构设计:工具返回值设计(OpenClaw、Claude Code、Hermes Agent 对比)
数据库
windawdaysss8 分钟前
离线学习SQL和数据库的工具及其部署
数据库·sql·学习
Rubin智造社8 分钟前
Claude Code开发者大会系列8:从脚本到智能体——独立开发者的“AI原生”工作流转型
数据库·人工智能·独立开发者·agentic工作流·ai原生开发·实操指南
一条泥憨鱼8 分钟前
深入理解 MySQL 索引:原理、分类与优化实战
数据库·mysql
楠枬8 分钟前
Redis 缓存
数据库·redis·缓存
一条泥憨鱼8 分钟前
详解MySQL事务(超详细版)
java·数据库·mysql·spring·maven·后端开发
j7~10 分钟前
【MYSQL】 数据库的常见数据类型--详解
数据库·mysql·decimal·varchar·数据库的基本类型