package com.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import com.interceptor.AuthorizationInterceptor; /** * Spring MVC 全局拦截器与静态资源配置类 * *
核心职责: *
注意事项: * 继承 {@link WebMvcConfigurationSupport} 会覆盖Spring Boot的自动配置, * 需要手动处理静态资源映射,否则会导致静态资源无法访问。 * * @author YourName * @version 1.0 * @since 2023-10-01 */ @Configuration // 声明此类为Spring配置类 public class InterceptorConfig extends WebMvcConfigurationSupport { /** * 创建授权拦截器Bean * *
使用 {@code @Bean} 注解将拦截器实例纳入Spring容器管理, * 确保拦截器中的依赖注入能正常工作。 * * @return 初始化完成的授权拦截器实例 */ @Bean public AuthorizationInterceptor getAuthorizationInterceptor() { return new AuthorizationInterceptor(); } /** * 注册拦截器并配置拦截规则 * *
拦截配置说明: *
典型应用场景: *
必要性:当覆盖 {@code WebMvcConfigurationSupport} 时, * Spring Boot的默认静态资源配置会失效,必须手动指定资源映射。 * *
资源位置说明: *
| 路径模式 | 物理位置 | 典型内容 |
|---|---|---|
| /** | classpath:/resources/ | XML配置文件 |
| /** | classpath:/static/ | CSS/JS/图片 |
| /** | classpath:/admin/ | 后台管理界面资源 |
| /** | classpath:/front/ | 前端界面资源 |
| /** | classpath:/public/ | 公共资源 |
特殊说明: * 在Spring Boot中,通常不需要此配置,除非需要完全自定义MVC行为。 * * @param registry 资源处理器注册器 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 配置静态资源映射 registry.addResourceHandler("/**") // 匹配所有URL路径 .addResourceLocations("classpath:/resources/") // 资源位置1 .addResourceLocations("classpath:/static/") // 资源位置2 .addResourceLocations("classpath:/admin/") // 资源位置3 .addResourceLocations("classpath:/front/") // 资源位置4 .addResourceLocations("classpath:/public/"); // 资源位置5 // 保留父类配置(可选) super.addResourceHandlers(registry); } }