从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
的信息?还是这是一个错误?