Spring Boot 2.1.7中SecurityFilterChain无法注入HttpSecurity的问题
问题根源
你使用的Spring Boot 2.1.7.RELEASE对应的Spring Security版本是5.1.x,而SecurityFilterChain这种基于Bean的配置方式是Spring Security 5.4及以上版本才引入的新特性。在5.1.x版本中,Spring容器不会自动创建HttpSecurity类型的Bean,也不支持通过@Bean定义SecurityFilterChain来配置安全规则,这就是启动时找不到Bean的根本原因。
解决方案
方案一:升级Spring Boot版本(推荐)
Spring Boot 2.4.0及以上版本对应Spring Security 5.4+,完全支持SecurityFilterChain配置方式。你只需要修改pom.xml中的父版本:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.16</version> <!-- 选择稳定的新版本,如2.7.x系列 --> <relativePath/> </parent>
注意:升级后需要检查其他依赖的兼容性,你当前使用的mybatis-spring-boot-starter 3.0.2适配Spring Boot 2.7.x,无需修改;若有其他第三方依赖,可能需要调整对应版本。
方案二:退回到WebSecurityConfigurerAdapter配置(不升级版本时)
如果无法升级Spring Boot,必须使用低版本支持的WebSecurityConfigurerAdapter方式修改配置类,替代SecurityFilterChain:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/**/ajax/**").permitAll() .antMatchers("/login", "/login/process").permitAll() .antMatchers("/**").authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .loginProcessingUrl("/login/process") .usernameParameter("username") .passwordParameter("password") .defaultSuccessUrl("/") .failureUrl("/login?session=fail") .and() .logout() .deleteCookies("JSESSIONID") .logoutUrl("/logout") .logoutSuccessUrl("/login") .and() .httpBasic(); http.sessionManagement() .invalidSessionUrl("/login?session=timeout") .maximumSessions(1) .maxSessionsPreventsLogin(false) .expiredUrl("/login?session=dupli"); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
这种方式是Spring Security 5.4之前的标准配置方式,完全兼容Spring Boot 2.1.7版本,不需要额外的@ComponentScan配置。
关于@ComponentScan临时解决方案的说明
你添加@ComponentScan扫描Spring Security内部包的方式能临时解决问题,但不推荐:因为Spring Security的内部包(如org.springframework.security.config.annotation.web.builders)并非为用户手动扫描设计,可能导致容器中创建不必要的Bean,引发潜在的配置冲突或版本兼容问题。
内容的提问来源于stack exchange,提问作者seung hyun Cheon

