springboot的自定义注解使用

本文介绍了如何在Java中使用自定义注解配合拦截器(如HandlerInterceptor和Filter)实现请求预处理,以及AOP在控制请求流程中的应用。重点讨论了自定义注解在方法上的使用以及如何在过滤器中访问HandlerMapping信息。
摘要由CSDN通过智能技术生成

1.自定义注解配合拦截器

// 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    // 自定义注解的属性
}

// 控制器类
@RestController
public class MyController {

    @GetMapping("/myEndpoint")
    @MyAnnotation // 使用自定义注解
    public String myEndpoint() {
        return "Hello, World!";
    }
}

// 自定义拦截器
@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断请求方法上是否有自定义注解
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            MyAnnotation myAnnotation = handlerMethod.getMethod().getAnnotation(MyAnnotation.class);
            if (myAnnotation != null) {
                // 在这里处理自定义注解的逻辑
                System.out.println("Intercepted request with MyAnnotation");
            }
        }
        return true;
    }

    // 省略postHandle()和afterCompletion()方法
}

// 注册拦截器
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    private final MyInterceptor myInterceptor;

    public InterceptorConfig(MyInterceptor myInterceptor) {
        this.myInterceptor = myInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}

2. 自定义注解与过滤器(需要前端约定好一个属性,不推荐)

// 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    // 自定义注解的属性
}

// 控制器类
@RestController
public class MyController {

    @GetMapping("/myEndpoint")
    @MyAnnotation // 使用自定义注解
    public String myEndpoint() {
        return "Hello, World!";
    }
}

// 自定义过滤器
@Component
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        /** 判断请求方法上是否有自定义注解
			过滤器在请求到达DispatchServlet之前执行,可以用于对
			请求进行预处理和过滤。DispatchServlet负责处理请求的
			分发和后续的处理逻辑。HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE属性
			是在DispatchServlet的请求处理阶段赋值的,它存储了最佳匹配的处理器信息。只有
			当请求到达DispatchServlet并且经过HandlerMapping的匹配过程后,才会有该属性的值。
			在过滤器(Filter)中,默认情况下是无法直接获取到	HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE属性的。
			如果在过滤器中需要获取HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE属性,一种可行的方式是在过滤器中将该属性保存到请求的属性中,然后在后续的处理环节中再进行获取。具体的做法可以通过自定义的HttpServletRequestWrapper或者自定义的Filter来实现。
		*/
        HandlerMethod handlerMethod = (HandlerMethod) httpRequest.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
        if (handlerMethod != null) {
            MyAnnotation myAnnotation = handlerMethod.getMethod().getAnnotation(MyAnnotation.class);
            if (myAnnotation != null) {
                // 在这里处理自定义注解的逻辑
                System.out.println("Filtered request with MyAnnotation");
            }
        }

        // 继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁方法
    }
}

// 注册过滤器
@Configuration
public class FilterConfig {

    private final MyFilter myFilter;

    public FilterConfig(MyFilter myFilter) {
        this.myFilter = myFilter;
    }

    @Bean
    public FilterRegistrationBean<MyFilter> myFilterRegistration() {
        FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>(myFilter);
        registration.addUrlPatterns("/*");
        return registration;
    }
}

3.AOP …

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值