How to target specific handlers with a @ControllerAdvice @ModelAttribute?

时光毁灭记忆、已成空白 提交于 2019-12-02 01:08:24

A controller advice can be limited to certain controllers (not methods) by using one of the values of the @ControllerAdvice annotation, e.g.

@ControllerAdvice(assignableTypes = {MyController1.class, MyController2.class})

If you need to do it on a method level I suggest to take a look at Interceptors.

Thanks to @zeroflagL for pointing me to the interceptor solution. I ditched the @ControllerAdvice approach and ended up with this:

Custom annotation:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MaintAware {
    String name() default "MaintAware";
}

Interceptor:

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    HandlerMethod handlerMethod = (HandlerMethod)handler;
    Method method = handlerMethod.getMethod();
    MaintAware maintAware = method.getAnnotation(MaintAware.class);
    if (maintAware != null) {
        Locale locale = request.getLocale();
        if (isMaintenanceWindowSet() && !isMaintenanceInEffect()) {
            String msg = getImminentMaint(locale);
            if (!msg.isEmpty())
                modelAndView.addObject("warningMaint", msg);
        }
    }

    super.postHandle(request, response, handler, modelAndView);
}

Now I can annotate the specific methods that require the maintenance notification. Easy peasy. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!