我偶然發現了一個從遺留 spring 轉換為 Spring Boot 的專案的配置類。我看到有兩種添加攔截器的方法。像這些
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor( new MyInterceptorOne()).addPathPatterns("/api/data/**");
}
@Bean
public MappedInterceptor mappedResponseHeaderInterceptor() {
return new MappedInterceptor(new String[] { "/static/css/**", "/static/img/**" }, new ResponseHeaderInterceptor());
}
}
兩個攔截器都在作業。我想知道在 Spring Boot 中添加攔截器的正確方法是什么以及為什么存在這兩種方法
uj5u.com熱心網友回復:
基本上它們是一樣的。
registry.addInterceptor( new MyInterceptorOne()).addPathPatterns("/api/data/**");
將在內部使用MappedInterceptor來注冊HandlerInterceptor具有給定 URL 模式的 。
現在將 a HandlerInterceptor(MappedInterceptor實作)注冊為 an@Bean有效,因為 Spring Boot(不是普通的 Spring!)檢測HandlerInterceptor背景關系中的 bean 并自動為您注冊它們。這在常規 Spring 應用程式中不起作用。
所以使用的方法是使用InterceptorRegistryas 那是記錄的方式,MappedInterceptor更多的是內部支持類。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/346848.html
上一篇:SpringSecurity與Chrome一起使用,但允許未經授權從Postman獲取
下一篇:使用Gradle匯入專案springboot出現錯誤:無法應用插件'org.springframework.boot'
