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

排除SecurityAutoConfiguration后API出现404错误,求解决方案

解决思路与可行方案

问题根源

  1. 组件扫描范围过窄:你的@ComponentScan仅指定了com.example.policymanagementsystem.bean包,导致控制器(Controller)、安全配置类(SecurityConfiguration)等核心组件未被Spring容器加载,直接引发API 404。
  2. 安全配置逻辑冲突:当前configure(HttpSecurity)方法中anyRequest().authenticated()会要求非/admin/**、/user/**的请求必须认证,不符合你「所有API无需认证」的需求;且排除SecurityAutoConfiguration后,自定义安全配置类未被正确识别加载。

具体修复步骤

1. 修正主类的组件扫描范围

去掉@ComponentScan的窄范围配置,因为@SpringBootApplication默认会扫描主类所在包(com.example.policymanagementsystem)及其所有子包,足以覆盖控制器、配置类、Bean等所有组件。如果必须保留@ComponentScan,需补充所有需要扫描的包:

package com.example.policymanagementsystem;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
// 若需自定义扫描范围,补充所有必要包,比如controller、config等
// @ComponentScan(basePackages = {"com.example.policymanagementsystem.bean", "com.example.policymanagementsystem.controller", "com.example.policymanagementsystem.config"})
public class PolicymanagementsystemApplication {

    public static void main(String[] args) {
        SpringApplication.run(PolicymanagementsystemApplication.class, args);
    }
}

2. 完善自定义安全配置类

确保配置类上添加@Configuration和@EnableWebSecurity注解,让Spring识别为安全配置类;同时调整configure(HttpSecurity)逻辑,允许所有请求无需认证:

package com.example.policymanagementsystem.config; // 确保此包在主类扫描范围内

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 允许跨域、关闭CSRF保护
        http.cors().and().csrf().disable();
        
        // 所有请求都允许匿名访问(无需认证)
        http.authorizeRequests()
            .anyRequest().permitAll();
            
        // 移除认证入口和JWT过滤器(因为不需要认证),如果你的业务不需要JWT验证的话
        // 若仍需保留JWT过滤器,需确保过滤器不会拦截无token的请求,否则会返回401
        // http.exceptionHandling().authenticationEntryPoint(...);
        // http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

3. 验证控制器类的包路径

确保你的API控制器类所在包(比如com.example.policymanagementsystem.controller)在主类的扫描范围内,控制器类上添加@RestController或@Controller注解。


验证效果

启动应用后,日志不再生成默认安全密码,同时通过Postman调用所有API时,会正常返回业务响应而非404或401。

内容的提问来源于stack exchange,提问作者Diptesh karle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:10:41