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

Spring Boot启动失败:无法找到UsuarioServiceImpl Bean求助

Spring Boot Security模块启动失败问题排查与解决

错误信息

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
08:24 ERROR 18740 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field usuarioServicio in com.example.demo4.security.SecurityConfiguration required a bean of type 'com.example.demo4.service.UsuarioServiceImpl' that could not be found.

The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true) 

核心问题与修复步骤

1. 依赖注入改为接口类型(关键修复)

Spring容器默认会将标注@Service的实现类注册为对应接口类型的Bean,而非实现类本身。直接注入实现类会导致容器无法匹配到对应Bean。

修改SecurityConfiguration类

将注入的UsuarioServiceImpl改为接口UsuarioService,并修复PasswordEncoder的未注入问题:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Autowired
    private UsuarioService usuarioServicio; // 改为接口类型

    @Autowired
    private PasswordEncoder passwordEncoder; // 注入PasswordEncoder Bean

    AuthenticationManager authenticationManager;

    @Bean
    public SecurityFilterChain filterChain (HttpSecurity http) throws Exception{
        AuthenticationManagerBuilder builder =http.getSharedObject(AuthenticationManagerBuilder.class);
        builder.userDetailsService(usuarioServicio).passwordEncoder(passwordEncoder);
        authenticationManager = builder.build();
        http.authenticationManager(authenticationManager);

        http.csrf(csrf -> csrf.disable());
        http.cors(Customizer.withDefaults());
        http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        // 修正路径匹配符为**,匹配所有子路径资源
        http.authorizeHttpRequests(auth -> auth.requestMatchers("/registro", "/js/**","/css/**", "/img/**")
                .permitAll()
                .anyRequest()
                .authenticated());
        return http.build();
    }

    @Bean 
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
        auth.setUserDetailsService(usuarioServicio);
        auth.setPasswordEncoder(passwordEncoder());
        return auth;
    }
}

修改RegistroUsuarioControlador类

同样将注入类型改为接口:

@Controller
@RequestMapping("/registro")
public class RegistroUsuarioControlador {
    
    @Autowired
    private UsuarioService usuarioServicio; // 改为接口类型

    @ModelAttribute("usuario")
    public UsuarioRegistroDTO retornarNuevoUsuarioRegistroDTO() {
        return new UsuarioRegistroDTO();
    }

    @GetMapping
    public String mostrarFormularioDeRegistro(){
        return "registro";
    }

    @PostMapping
    public String registrarCuentaDeUsuario(@ModelAttribute("usuario") UsuarioRegistroDTO registroDTO){
        usuarioServicio.guardar(registroDTO);
        return "redirect:/registro?exito";
    }
}

2. 检查包扫描范围

确保UsuarioServiceImpl所在的com.example.demo4.service包是Demo4Application(根包com.example.demo4)的子包。@SpringBootApplication默认会扫描当前包及其所有子包下的组件,若Service类不在该范围内,需手动添加扫描路径:

@SpringBootApplication(scanBasePackages = "com.example.demo4")
public class Demo4Application {
    public static void main(String[] args) {
        SpringApplication.run(Demo4Application.class, args);
    }
}

3. 移除冲突配置

application.properties中默认用户配置会与自定义UserDetailsService冲突,建议删除以下两行:

# security
spring.security.user.name=usuario
spring.security.user.password=psw

额外优化点

  • 路径匹配符使用/**代替/,确保能匹配所有子路径下的静态资源。
  • 推荐使用构造方法注入替代字段注入,提升代码可测试性与稳定性。

内容的提问来源于stack exchange,提问作者Angel CR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:44:56