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

Spring Security报错:antMatchers()方法未定义问题求助

Spring Security配置类中antMatchers方法报错解决方案

我正在学习Spring Security时编写了如下配置类:

package com.nikola.security;

import org.springframework.context.annotation.Bean;
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.web.SecurityFilterChain;

@Configuration //klasata mora da bide anotirana so @Configuration bidejki e configuration klasa
@EnableWebSecurity //so anotiranje na @EnableWebSecurity kazuvame deka vo ovaa klasa ke implementirame se
//za security za nasata aplikacija
public class ApplicationSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception  {
        
        http
        .authorizeHttpRequests()//authoriziraj gi
        .antMatchers("/","index","/css/*","/js/*")
        .permitAll()
        .anyRequest()//sekoj request 
        .authenticated()//mora da bide avtenticiran 
        .and()//i
        .httpBasic();//mehanizmot koi sakame da go koristime e http Basic
        return http.build();
    }
}

运行时出现如下错误:

Description Resource    Path    Location    Type
The method antMatchers(String, String, String, String) is undefined for the type AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry   ApplicationSecurityConfig.java  /Spring-Boot-Security-Tutorial-NovoVideo/src/main/java/com/nikola/security  line 19 Java Problem

解决方法

Spring Security 6.x版本移除了antMatchers方法,改用requestMatchers替代,修改配置类中的对应代码即可:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception  {
    
    http
    .authorizeHttpRequests()
    .requestMatchers("/","/index","/css/*","/js/*") // 替换antMatchers为requestMatchers,同时修正index路径为/index
    .permitAll()
    .anyRequest()
    .authenticated()
    .and()
    .httpBasic();
    return http.build();
}

说明

  • 视频使用的是Spring Security 5.x版本,该版本中antMatchers是可用的;但6.x版本已将其移除,统一使用requestMatchers。
  • 注意路径"index"建议改为"/index",避免路径匹配时出现歧义,确保精确匹配根路径下的index页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:20:33