Desarrollo de anotaciones SpringBoot

paso:

  1. clase de anotación de escritura
  2. Configure el interceptor para implementar la interfaz HandlerInterceptor, reescriba los métodos preHandle y afterCompletion y procese las transacciones antes (después) de la intercepción.
  3. Agregar interceptor en la clase de configuración WebMvc

Clase de anotación:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 设置运行时有效
@Retention(RetentionPolicy.RUNTIME)
// 设置方法上时有效
@Target(ElementType.METHOD)
public @interface AccessLimit {
    
    
    // 单位时间
    int second();

    // 最大请求次数
    int maxCount();

    // 是否需要登录
    boolean needLogin() default true;
}

interceptador


    /**
     * 在请求前处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
    	// True表示不拦截、false表示拦截
        return true;
    }

Agregar interceptor en webmvc

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    
    
    
    @Autowired
    private AccessLimitInterceptor accessLimitInterceptor;

    /**
     * 添加拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(accessLimitInterceptor);
    }
}

Supongo que te gusta

Origin blog.csdn.net/weixin_43960044/article/details/124014462
Recomendado
Clasificación