问题的产生:在开发项目使用拦截器的时候,发现每个子项目都需要配置拦截器,而且许多路由接口都需要配置不同的拦截器,每次都需要重新找到拦截器配置文件去注册一个新的拦截器,非常的麻烦,就想,能不能有个注解可以给特定的路由接口配置特定的拦截器。

问题调查:

        1. 经调查,有许多人都多 @RequestMapping 注解可以使用 interceptor 属性来指定特定的拦截器,但是我发现并不行,而且没有该参数,源码如下。感兴趣的人可以自己调查。

 注解开发

        1. 首先自定义一个注解类

public @interface CustomInterceptors {
    String[] value();
}

         2.在拦截器配置类中注册一个拦截器,然后检查该路由接口上是否有自定义的注解 @CustomInterceptors。如果有,执行该拦截器

@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                if (handler instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    Interceptors methodInterceptors = handlerMethod.getMethod().getAnnotation(Interceptors.class);

                    // Handle method-level interceptors
                    if (methodInterceptors != null) {
                        for (String interceptorName : methodInterceptors.value()) {
                            HandlerInterceptor interceptor = (HandlerInterceptor) applicationContext.getBean(interceptorName);
                            boolean shouldContinue = interceptor.preHandle(request, response, handler);
                            if (!shouldContinue) {
                                return false;
                            }
                        }
                    }
                }
                return true;
            }
        });
    }

        3. 如果需要抽取成为一个公用的子项目,然后分别导入到各个子项目中,那么需要将该配置类导入到对应子项目

@SpringBootApplication
@ComponentScan(basePackages = {"com.demo.*", "com.custom.interceptor.*"})
@Import(InterceptorConfiguration.class)
public class DemoApplication {

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

}

注:该方法有一种问题,请注意,如果子项目中有单独的拦截器需要注册,那么一定要注意不要残生冲突。

要解决这个问题,可以使用SpringBoot的条件注解,自动配置,欢迎留言讨论

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐