拦截器获取controller上的自定义注解
拦截器获取controller上的注解
RateLimit 为自定义注解
if (handler instanceof HandlerMethod) {HandlerMethod method = (HandlerMethod) handler;if (method != null) {//获取方法上的注解RateLimit myannoaction = method.getMethodAnnotation(RateLimit.class);}}
完整示例
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("preHandle 我在方法执行前面执行 " + System.currentTimeMillis());if (handler instanceof HandlerMethod) {HandlerMethod method = (HandlerMethod) handler;if (method != null) {//获取方法上的注解RateLimit myannoaction = method.getMethodAnnotation(RateLimit.class);}}return true; //返回true才能继续往下}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("postHandle (没发生异常的情况下)我在方法执行完后执行 " + System.currentTimeMillis());}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("afterCompletion 不管方法是否发生异常,我都在完成后执行 " + System.currentTimeMillis());}
}
传送门
springboot基础(59):自定义拦截器