Spring源码阅读(八)-IOC之AnnotationConfigApplicationContext
说明
现在一般都是用注解的方式,而不是xml配置方式所以还是准备看一下AnnotationConfigApplicationContext源码
使用例子
public static void main(String[] args) { // AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext("org.springframework.lqtest"); //AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(BeanRegisterConfig.class,CommentTest.class); //<1>构造函数初始化 AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(); //<2>直接加载指定class对应的BeanDefinition到容器 applicationContext.register(BeanRegisterConfig.class,CommentTest.class); //<10>解析指定包下的class对应的BeanDefinition到容器 applicationContext.scan("org.springframework.lqtest"); //<**>初始化容器 主要是通过BeanDefinition完成初始化对象 applicationContext.refresh(); String [] names=applicationContext.getBeanDefinitionNames(); for (String name: names) { System.out.println(name); } }
<1>
public AnnotationConfigApplicationContext() { //class的解析器 this.reader = new AnnotatedBeanDefinitionReader(this); //包解析器 this.scanner = new ClassPathBeanDefinitionScanner(this); }
<2>
org.springframework.context.annotation.AnnotationConfigApplicationContext#register
@Override public void register(Class<?>... componentClasses) { Assert.notEmpty(componentClasses, "At least one component class must be specified"); //<3>委托给AnnotatedBeanDefinitionReader处理 this.reader.register(componentClasses); }
<3>
org.springframework.context.annotation.AnnotatedBeanDefinitionReader#register
public void register(Class<?>... componentClasses) { for (Class<?> componentClass : componentClasses) { //<4>加载 registerBean(componentClass); } }
<4>
org.springframework.context.annotation.AnnotatedBeanDefinitionReader#registerBean
public void registerBean(Class<?> beanClass) { //<5> doRegisterBean(beanClass, null, null, null, null); }
<5>
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); //<6>根据@Condition注解判断是否加载 if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) { return; } /** * supplier 可以自定义实现初始化方法 * applicationContext.registerBean(User.class,new Supplier(){ * @Override * public Object get() { * User user=new User(); * return user; * } * }); **/ abd.setInstanceSupplier(supplier); //解析@Scope配置封装到ScopeMetadata, 默认为singleton 单例,可选为singleton,prototype,request,session,global session ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); abd.setScope(scopeMetadata.getScopeName()); //<8>获取bean的nanme String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); //<9>根据元数据上的注解配置设置到BeanDefinition 如@Lazy @Primary等注解 AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); //通过register方法直接配置 谁知道beanDefinition this.registerBean(User.class,qualifiers=new Class[]{Primary.class,Lazy.class}); if (qualifiers != null) { for (Class<? extends Annotation> qualifier : qualifiers) { if (Primary.class == qualifier) { abd.setPrimary(true); } else if (Lazy.class == qualifier) { abd.setLazyInit(true); } else { abd.addQualifier(new AutowireCandidateQualifier(qualifier)); } } } //提供钩子方法允许对beanDefinition自定义设置 if (customizers != null) { for (BeanDefinitionCustomizer customizer : customizers) { customizer.customize(abd); } } //封装到BeanDefinitionHolder BeanDefinitionHolder持有BeanDefinition BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName); //通过解析@Scoep的proxMode属性判断是否使用代理默认是No 可选INTERFACES_jdk代理,TARGET_CLASS_CGlib definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); //注册到registry就是我们的BeanFactory,BeanFactory实现类也实现了registry BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); }
<6>
org.springframework.context.annotation.ConditionEvaluator#shouldSkip(org.springframework.core.type.AnnotatedTypeMetadata)
public boolean shouldSkip(AnnotatedTypeMetadata metadata) { //<7> return shouldSkip(metadata, null); }
<7>
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) { //判断是否打了Conditional 注解 if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) { return false; } //如果注册阶段为空 if (phase == null) { //判断是否是@Component @ComponentScan @Import @Import的类上打了Conditional注解 if (metadata instanceof AnnotationMetadata && ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) { return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION); } //非以上注解则是注册 return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN); } //从@Condition 获取类 List<Condition> conditions = new ArrayList<>(); for (String[] conditionClasses : getConditionClasses(metadata)) { for (String conditionClass : conditionClasses) { Condition condition = getCondition(conditionClass, this.context.getClassLoader()); conditions.add(condition); } } //根据sort排序 AnnotationAwareOrderComparator.sort(conditions); for (Condition condition : conditions) { ConfigurationPhase requiredPhase = null; //如果实现了ConfigurationCondition 则需要校验阶段 if (condition instanceof ConfigurationCondition) { requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase(); } //阶段一致才执行match方法 if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) { return true; } } return false; }
<8>
org.springframework.context.annotation.AnnotationBeanNameGenerator#generateBeanName
@Override public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { //先尝试根据注解获取beanName if (definition instanceof AnnotatedBeanDefinition) { String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition); if (StringUtils.hasText(beanName)) { // Explicit bean name found. return beanName; } } //没有定义beanName根据class name生成 return buildDefaultBeanName(definition, registry); }
<9>
org.springframework.context.annotation.AnnotationConfigUtils#processCommonDefinitionAnnotations
static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) { //延迟加载 AnnotationAttributes lazy = attributesFor(metadata, Lazy.class); if (lazy != null) { //如果打了Lazy注解,则设置对应值到BeanDefinition abd.setLazyInit(lazy.getBoolean("value")); } else if (abd.getMetadata() != metadata) { lazy = attributesFor(abd.getMetadata(), Lazy.class); if (lazy != null) { //如果打了Lazy注解,则设置对应值到BeanDefinition abd.setLazyInit(lazy.getBoolean("value")); } } //使用@Autowired注入同一个类型多个实例,优先注入Primary if (metadata.isAnnotated(Primary.class.getName())) { //如果打了Primary注解,则设置对应值到BeanDefinition abd.setPrimary(true); } //加载顺序 可以定义在方法和类上 如当eventListener初始化后才会初始化EventSource // @Bean // @DependsOn(value = {"eventListener"}) // public EventSource eventSource(){ // return new EventSource(); // } AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class); if (dependsOn != null) { //如果打了DependsOn注解,则设置对应值到BeanDefinition abd.setDependsOn(dependsOn.getStringArray("value")); } AnnotationAttributes role = attributesFor(metadata, Role.class); if (role != null) { //如果打了@Role注解,则设置对应值到BeanDefinition abd.setRole(role.getNumber("value").intValue()); } AnnotationAttributes description = attributesFor(metadata, Description.class); if (description != null) { //如果打了@Description注解,则设置对应值到BeanDefinition abd.setDescription(description.getString("value")); } }
<10>
org.springframework.context.annotation.AnnotationConfigApplicationContext#scan
@Override public void scan(String... basePackages) { Assert.notEmpty(basePackages, "At least one base package must be specified"); //<11>委托给ClassPathBeanDefinitionScanner处理 this.scanner.scan(basePackages); }
<11>
org.springframework.context.annotation.ClassPathBeanDefinitionScanner#scan
public int scan(String... basePackages) { int beanCountAtScanStart = this.registry.getBeanDefinitionCount(); //<12>真正扫描包加载的方法 doScan(basePackages); //<13>注册一批实现了BeanProcess的配置类默认true if (this.includeAnnotationConfig) { AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); } return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart); }
<12>
org.springframework.context.annotation.ClassPathBeanDefinitionScanner#doScan
protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Assert.notEmpty(basePackages, "At least one base package must be specified"); Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>(); for (String basePackage : basePackages) {
//<15>扫描包获取BeanDefinition Set<BeanDefinition> candidates = findCandidateComponents(basePackage); for (BeanDefinition candidate : candidates) { //获得@Scope配置信息 ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate); //解析@Scope配置封装到ScopeMetadata, 默认为singleton 单例,可选为singleton,prototype,request,session,global session candidate.setScope(scopeMetadata.getScopeName()); //<8>获取bean的nanme String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry); if (candidate instanceof AbstractBeanDefinition) { postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName); } if (candidate instanceof AnnotatedBeanDefinition) { //<9>根据元数据上的注解配置设置到BeanDefinition 如@Lazy @Primary等注解 AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate); } //避免重复加载 从beanDefinitionMap校验当前beanName是否存在 if (checkCandidate(beanName, candidate)) { //封装到BeanDefinitionHolder BeanDefinitionHolder持有BeanDefinition BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName); //通过解析@Scoep的proxMode属性判断是否使用代理默认是No 可选INTERFACES_jdk代理,TARGET_CLASS_CGlib definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); beanDefinitions.add(definitionHolder); //注册到registry就是我们的BeanFactory,BeanFactory实现类也实现了registry registerBeanDefinition(definitionHolder, this.registry); } } } return beanDefinitions; }
<13>
org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) { //<14> registerAnnotationConfigProcessors(registry, null); }
<14>
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors( BeanDefinitionRegistry registry, @Nullable Object source) { //beanFactory实现类实现了registry接口这里就是将registry转回BeanFactory DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { //注册了实现Order接口的排序器 beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); } //设置@AutoWired的候选的解析器 if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) { beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); } } Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8); /** * 注册解析我们配置类的后置处理器ConfigurationClassPostProcessor * org.springframework.context.annotation.internalConfigurationAnnotationProcessor */ if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)); } /** * 注册处理@Autowired 注解的处理器AutowiredAnnotationBeanPostProcessor * org.springframework.context.annotation.internalAutowiredAnnotationProcessor */ if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); } /** * 注册处理JSR规范的注解处理器CommonAnnotationBeanPostProcessor * org.springframework.context.annotation.internalCommonAnnotationProcessor */ if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); } /** * 处理jpa注解的处理器org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor */ if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(); try { def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, AnnotationConfigUtils.class.getClassLoader())); } catch (ClassNotFoundException ex) { throw new IllegalStateException( "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex); } def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)); } /** * 处理监听方法的注解解析器EventListenerMethodProcessor */ if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME)); } /** * 注册事件监听器工厂 */ if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME)); } return beanDefs; }
<15>
org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#findCandidateComponents
public Set<BeanDefinition> findCandidateComponents(String basePackage) { if (this.componentsIndex != null && indexSupportsIncludeFilters()) { return addCandidateComponentsFromIndex(this.componentsIndex, basePackage); } else { //<16>扫描包 return scanCandidateComponents(basePackage); } }
<16>
org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#scanCandidateComponents
private Set<BeanDefinition> scanCandidateComponents(String basePackage) { Set<BeanDefinition> candidates = new LinkedHashSet<>(); try { //拼接成classpath*:org/springframework/lqtest/**/*.class String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(basePackage) + '/' + this.resourcePattern; //委托给PathMatchingResourcePatternResolver 找到class patch下的class文件地址信息 Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath); boolean traceEnabled = logger.isTraceEnabled(); boolean debugEnabled = logger.isDebugEnabled(); for (Resource resource : resources) { if (traceEnabled) { logger.trace("Scanning " + resource); } try { //委托给CachingMetadataReaderFactory 获取class的元数据信息 MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource); //通过excludeFilters includeFilters 判断是否进行加载 if (isCandidateComponent(metadataReader)) { ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader); sbd.setSource(resource); if (isCandidateComponent(sbd)) { if (debugEnabled) { logger.debug("Identified candidate component class: " + resource); } candidates.add(sbd); } else { if (debugEnabled) { logger.debug("Ignored because not a concrete top-level class: " + resource); } } } else { if (traceEnabled) { logger.trace("Ignored because not matching any filter: " + resource); } } } catch (FileNotFoundException ex) { if (traceEnabled) { logger.trace("Ignored non-readable " + resource + ": " + ex.getMessage()); } } catch (Throwable ex) { throw new BeanDefinitionStoreException( "Failed to read candidate component class: " + resource, ex); } } } catch (IOException ex) { throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex); } return candidates; }