项目启动时报错找不到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();
    }
}
相关推荐
TDengine (老段)4 小时前
TDengine 第三方工具 — Telegraf、Kafka Connect、Flink、Spark
大数据·数据库·物联网·flink·kafka·时序数据库·tdengine
小白勇闯网安圈12 小时前
Django 响应对象、文件上传与类视图
数据库·django·sqlite
努力的小雨13 小时前
同一份 SQL 跑多套环境:Ksql 变量怎么用才安全
数据库
科技绘图14 小时前
快鲸GEO vs 传统AI搜索优化:全链路自动化与高效内容生产在转化闭环上的对比
数据库·人工智能·自动化
ltl14 小时前
数据库作为 LLM 记忆体:语义缓存、RAG 与一致性
数据库
ltl14 小时前
WAL 与崩溃恢复:ARIES 协议怎么跑通
数据库
ltl14 小时前
TEE 数据库:EnclaveDB、Oblivious 原语与机密 SQL
数据库
麻瓜code15 小时前
【Mysql】重新学一遍 SQL 执行顺序
数据库·sql
这个DBA有点耶16 小时前
数据库一体机架构演进:从硬件堆叠到软硬深度耦合
服务器·网络·数据库·硬件架构·运维开发·database·数据库架构
一只fish16 小时前
优化器架构对比:Oracle vs PostgreSQL vs MySQL
mysql·postgresql·oracle