You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security启动报错:找不到UserDetailsService类型Bean

问题解决:Spring Security启动时找不到UserDetailsService Bean

错误原因

启动报错是因为MySecurityConfig的authManager方法里声明了UserDetailsService类型的参数,但你既没在容器中注册这个类型的Bean,而且这个参数在你的自定义认证逻辑里完全没用——你已经通过MyAuthenticationProvider实现了独立的认证逻辑,根本不需要依赖UserDetailsService。另外BCryptPasswordEncoder参数也没被用到,可以一起删掉。

修改方案

直接修改MySecurityConfig中的authManager方法,移除多余的参数:

修改后的MySecurityConfig.java

@Configuration
public class MySecurityConfig {

    @Autowired
    private MyAuthenticationProvider authenticationProvider;

    @Bean
    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
                .authenticationProvider(authenticationProvider)
                .build();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.httpBasic();
        http.authorizeHttpRequests().anyRequest().authenticated();
        return http.build();
    }

    @Bean
    public static BCryptPasswordEncoder bcryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

额外说明

如果后续你需要切换到基于数据库的用户认证(比如从DB读取用户信息),再去实现UserDetailsService接口并把它注册为Spring Bean即可,但当前你的自定义AuthenticationProvider已经硬编码了认证逻辑,不需要这个组件。

其他代码(MyAuthenticationProvider、Controller、pom.xml)保持原样即可,启动后访问/hello用用户名tom、密码abc就能正常认证。

内容的提问来源于stack exchange,提问作者Aneesh Das Mazumder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:22:30