@ControllerAdvice组件不考虑有序接口

时间:2018-08-17 13:26:00

标签: spring spring-mvc

从Spring Javadoc:Ordered注释的类应同时支持@Order接口和@ControllerAdvice注释。但这不适用于我的异常处理程序:

  
@ControllerAdvice(annotations = Controller.class)
public class MyExceptionHandler implements Ordered {...}

研究了https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html源代码并在调试过程中,发现我不考虑使用Ordered

private ControllerAdviceBean(Object bean, @Nullable BeanFactory beanFactory) {
    this.bean = bean;
    this.beanFactory = beanFactory;
    Class<?> beanType;

    if (bean instanceof String) {
        String beanName = (String) bean;
        Assert.hasText(beanName, "Bean name must not be null");
        Assert.notNull(beanFactory, "BeanFactory must not be null");
        if (!beanFactory.containsBean(beanName)) {
            throw new IllegalArgumentException("BeanFactory [" + beanFactory +
                    "] does not contain specified controller advice bean '" + beanName + "'");
        }
        beanType = this.beanFactory.getType(beanName);
        // only this code is executed !!!
        // this uses only @Order annotation 
        this.order = initOrderFromBeanType(beanType); 
    }
    else {
        // dead code??? only String arguments are passed to this constructor by Spring
        Assert.notNull(bean, "Bean must not be null");
        beanType = bean.getClass();
        // this uses Ordered and @Order annotation
        this.order = initOrderFromBean(bean);  
    }
    ...
}

另请参见ControllerAdviceBean.findAnnotatedBeans()如何找到带注释的bean:

public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) {
    List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>();
    for (String name : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class)) {
        if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
            beans.add(new ControllerAdviceBean(name, applicationContext)); // String passed first argument
        }
    }

    return beans;
}

我是否缺少有关@ControllerAdvice的信息?还是这是一个错误?

0 个答案:

没有答案