org.springframework.web.method.ControllerAdviceBean#isApplicableToBeanType(@Nullable Class<?> beanType)
判断当前类是否被ControllerAdviceBean修饰,判断依据位 ControllerAdviceBean上设置的注解@ControllerAdvice内的参数
package org.springframework.web.bind.annotation; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; import org.springframework.stereotype.Component; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface ControllerAdvice { @AliasFor("basePackages") String[] value() default {}; @AliasFor("value") String[] basePackages() default {}; Class<?>[] basePackageClasses() default {}; Class<?>[] assignableTypes() default {}; Class<? extends Annotation>[] annotations() default {}; }
其内部使用 HandlerTypePredicate beanTypePredicate 进行判断,如果@ControllerAdvice注解内无参数 则可以修饰所有类。
由该段代码判断:
ControllerAdvice annotation = (beanType != null ? AnnotatedElementUtils.findMergedAnnotation(beanType, ControllerAdvice.class) : null); if (annotation != null) { this.beanTypePredicate = HandlerTypePredicate.builder() .basePackage(annotation.basePackages()) .basePackageClass(annotation.basePackageClasses()) .assignableType(annotation.assignableTypes()) .annotation(annotation.annotations()) .build(); } else { this.beanTypePredicate = HandlerTypePredicate.forAnyHandlerType(); }
HandlerTypePredicate.forAnyHandlerType(); 改方法实现如下:
return new HandlerTypePredicate(Collections.emptySet(), Collections.emptyList(), Collections.emptyList());
=====
实际会调用org.springframework.web.method.HandlerTypePredicate#test
if (!hasSelectors()) {
return true;
}
org.springframework.web.method.HandlerTypePredicate#hasSelectors private boolean hasSelectors() { return (!this.basePackages.isEmpty() || !this.assignableTypes.isEmpty() || !this.annotations.isEmpty()); }
org.springframework.web.method.ControllerAdviceBean#isApplicableToBeanType 作用