@Target({ElementType.METHOD}) // アノテーションはメソッドで使われる
@Retention(RetentionPolicy.RUNTIME) // アノテーションは実行時にも存在する
public @interface MyAnnotation {}
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
if(annotation != null) {
// 適宜処理する
}
return true;
}
}
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
/**
* インターセプターを追加する
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}