源码解析
如果没有@Configuration注解,这个类还能不能成为配置类呢?答案是可以的。
我们顺着源码看一下,在org.springframework.context.annotation.ConfigurationClassUtils#checkConfigurationClassCandidate里面进行了配置类的判断。如果是配置类,才进行我们熟知的扫描流程。
Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
......
else if (config != null || isConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}
上面的config如果没有@Configuration为空,进入了elseif这个分支,在这个分支里面对各自注解进行判断。
这个方法定义如下:
public static boolean isConfigurationCandidate(AnnotationMetadata metadata) {
// Do not consider an interface or an annotation...
if (metadata.isInterface()) {
return false;
}
// Any of the typical annotations found?
// 只要存在@Component、@ComponentScan、@Import、@ImportResource四个中的一个,就是lite配置类
for (String indicator : candidateIndicators) {
if (metadata.isAnnotated(indicator)) {
return true;
}
}
// Finally, let's look for @Bean methods...
// 只要存在@Bean注解了的方法,就是lite配置类
return hasBeanMethods(metadata);
}
从上面可以看出来只要存在@Component、@ComponentScan、@Import、@ImportResource四个中的一个,或者有@Bean注解了的方法就是配置类。
candidateIndicators注册的内容如下:
static {
candidateIndicators.add(Component.class.getName());
candidateIndicators.add(ComponentScan.class.getName());
candidateIndicators.add(Import.class.getName());
candidateIndicators.add(ImportResource.class.getName());
}
疑问
至于为什么我们写的自己定义的方法会进入这个分支,没看明白,也就是我们自己定义的配置类的BeanDefinition是AnnotatedBeanDefinition?为什么呢?
// 如果AnnotatedBeanDefinition,则直接取AnnotationMetadata
if (beanDef instanceof AnnotatedBeanDefinition &&
className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
// Can reuse the pre-parsed metadata from the given BeanDefinition...
metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
}
原来如此
我们再开始通过ioc容器进行了一次注册,也就是applicationContext.register(AppConfig.class);
所以我们在开始创建工厂的时候就有我们定义的appConfig。
我们再来回顾一下register方法。
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
@Nullable BeanDefinitionCustomizer[] customizers) {
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
追踪代码我们不难发现,doRegisterBean方法里面通过new AnnotatedGenericBeanDefinition(beanClass);产生了一个AnnotatedGenericBeanDefinition的bean,所以,在判断isConfigurationCandidate的时候,才是用AnnotatedGenericBeanDefinition去判断是不是候选的配置类。