目录
12、org.springframework.context.annotation.AnnotatedBeanDefinitionReader.register(Class...)
13、org.springframework.context.annotation.AnnotatedBeanDefinitionReader.registerBean(Class)
1、org.springframework.context.annotation.AnnotationConfigApplicationContext.AnnotationConfigApplicationContext(Class<?>...)
/** * Create a new AnnotationConfigApplicationContext, deriving bean definitions * from the given annotated classes and automatically refreshing the context. * @param annotatedClasses one or more annotated classes, * e.g. {@link Configuration @Configuration} classes */ //创建一个新的容器(AnnotationConfigApplicationContext), //并从给定的配置类中衍生出bean的定义(definitions) //并手动的刷新容器(context) public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { this(); register(annotatedClasses); refresh(); }
2、org.springframework.context.annotation.AnnotationConfigApplicationContext.AnnotationConfigApplicationContext()
/** * Create a new AnnotationConfigApplicationContext that needs to be populated * through {@link #register} calls and then manually {@linkplain #refresh refreshed}. */ //创建一个新的容器(AnnotationConfigApplicationContext ) //需要通过#register方法填充 //并手动刷新(#refresh) public AnnotationConfigApplicationContext() { this.reader = new AnnotatedBeanDefinitionReader(this); this.scanner = new ClassPathBeanDefinitionScanner(this); }
3、org.springframework.context.annotation.AnnotatedBeanDefinitionReader.AnnotatedBeanDefinitionReader(BeanDefinitionRegistry)
/** * @AnnotatedBeanDefinitionReader: * Convenient adapter for programmatic registration of annotated bean classes. * This is an alternative to {@link ClassPathBeanDefinitionScanner}, applying * the same resolution of annotations but for explicitly registered classes only. * * 方便适配以编程方式注册Bean的配置类 * 它是ClassPathBeanDefinitionScanner的替代方案 * 应用相同的注解方式,但是仅适用于显示注册的类 */ /** * Create a new {@code AnnotatedBeanDefinitionReader} for the given registry. * If the registry is {@link EnvironmentCapable}, e.g. is an {@code ApplicationContext}, * the {@link Environment} will be inherited, otherwise a new * {@link StandardEnvironment} will be created and used. * @param registry the {@code BeanFactory} to load bean definitions into, * in the form of a {@code BeanDefinitionRegistry} * @see #AnnotatedBeanDefinitionReader(BeanDefinitionRegistry, Environment) * @see #setEnvironment(Environment) */ //为给定的bean注册中心创建一个新的AnnotatedBeanDefinitionReader //如果注册中心是一个EnvironmentCapable(例如:ApplicationContext),Environment将会被继承 //否则一个新的StandardEnvironment将会被创建和使用 public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) { this(registry, getOrCreateEnvironment(registry)); }
3.1、org.springframework.context.annotation.AnnotatedBeanDefinitionReader.getOrCreateEnvironment(BeanDefinitionRegistry)
/** * Get the Environment from the given registry if possible, otherwise return a new * StandardEnvironment. */ private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); if (registry instanceof EnvironmentCapable) { return ((EnvironmentCapable) registry).getEnvironment(); } return new StandardEnvironment(); }
4、org.springframework.context.annotation.AnnotatedBeanDefinitionReader.AnnotatedBeanDefinitionReader(BeanDefinitionRegistry, Environment)
/** * Create a new {@code AnnotatedBeanDefinitionReader} for the given registry and using * the given {@link Environment}. * @param registry the {@code BeanFactory} to load bean definitions into, * in the form of a {@code BeanDefinitionRegistry} * @param environment the {@code Environment} to use when evaluating bean definition * profiles. * @since 3.1 */ //为给定的注册中心创建一个新的AnnotatedBeanDefinitionReader并且使用给定的Environment public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); Assert.notNull(environment, "Environment must not be null"); this.registry = registry; this.conditionEvaluator = new ConditionEvaluator(registry, environment, null); AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); }
5、org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors(BeanDefinitionRegistry)
/** * Register all relevant annotation post processors in the given registry. * @param registry the registry to operate on */ //在给定的注册中心中注册所有相关的注解后置处理器 public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) { registerAnnotationConfigProcessors(registry, null); }
6、org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors(BeanDefinitionRegistry, Object)
/** * Register all relevant annotation post processors in the given registry. * @param registry the registry to operate on * @param source the configuration source element (already extracted) * that this registration was triggered(触发) from. May be {@code null}. * @return a Set of BeanDefinitionHolders, containing all bean definitions * that have actually been registered by this call */ public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors( BeanDefinitionRegistry registry, Object source) { //返回此上下文的基础bean工厂,可用于注册bean定义。 DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); } if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) { beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); } } Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<BeanDefinitionHolder>(4); //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)); } //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)); } //org.springframework.context.annotation.internalRequiredAnnotationProcessor if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); } // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor. //检查对JSR-250的支持,如果存在,则添加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)); } // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor. //检查是否支持JPA,如果存在,则添加PersistenceAnnotationBeanPostProcessor。 //org.springframework.context.annotation.internalPersistenceAnnotationProcessor 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)); } //org.springframework.context.event.internalEventListenerProcessor 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)); } //org.springframework.context.event.internalEventListenerFactory 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; }
6.1、org.springframework.context.annotation.AnnotationConfigUtils.unwrapDefaultListableBeanFactory(BeanDefinitionRegistry)
private static DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) { if (registry instanceof DefaultListableBeanFactory) { return (DefaultListableBeanFactory) registry; } else if (registry instanceof GenericApplicationContext) { return ((GenericApplicationContext) registry).getDefaultListableBeanFactory(); } else { return null; } }
6.2、org.springframework.context.annotation.AnnotationConfigUtils.registerPostProcessor(BeanDefinitionRegistry, RootBeanDefinition, String)
private static BeanDefinitionHolder registerPostProcessor( BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) { definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(beanName, definition); return new BeanDefinitionHolder(definition, beanName); }
6.2.1、org.springframework.beans.factory.config.BeanDefinitionHolder.BeanDefinitionHolder(BeanDefinition, String, String[])
/** * Create a new BeanDefinitionHolder. * @param beanDefinition the BeanDefinition to wrap * @param beanName the name of the bean, as specified for the bean definition */ //创建一个新的BeanDefinitionHolder public BeanDefinitionHolder(BeanDefinition beanDefinition, String beanName) { this(beanDefinition, beanName, null); } /** * Create a new BeanDefinitionHolder. * @param beanDefinition the BeanDefinition to wrap * @param beanName the name of the bean, as specified for the bean definition * @param aliases alias names for the bean, or {@code null} if none */ public BeanDefinitionHolder(BeanDefinition beanDefinition, String beanName, String[] aliases) { Assert.notNull(beanDefinition, "BeanDefinition must not be null"); Assert.notNull(beanName, "Bean name must not be null"); this.beanDefinition = beanDefinition; this.beanName = beanName; this.aliases = aliases; }
7、org.springframework.context.annotation.ClassPathBeanDefinitionScanner.ClassPathBeanDefinitionScanner(BeanDefinitionRegistry)
/** * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory. * @param registry the {@code BeanFactory} to load bean definitions into, in the form * of a {@code BeanDefinitionRegistry} */ //为给定的bean factory创建一个新的ClassPathBeanDefinitionScanner //将bean definitions加载进BeanFactory中的BeanDefinitionRegistry中 public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { this(registry, true); }
8、org.springframework.context.annotation.ClassPathBeanDefinitionScanner.ClassPathBeanDefinitionScanner(BeanDefinitionRegistry, boolean)
/** * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory. * <p>If the passed-in bean factory does not only implement the * {@code BeanDefinitionRegistry} interface but also the {@code ResourceLoader} * interface, it will be used as default {@code ResourceLoader} as well. This will * usually be the case for {@link org.springframework.context.ApplicationContext} * implementations. * <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader} * will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}. * <p>If the passed-in bean factory also implements {@link EnvironmentCapable} its * environment will be used by this reader. Otherwise, the reader will initialize and * use a {@link org.springframework.core.env.StandardEnvironment}. All * {@code ApplicationContext} implementations are {@code EnvironmentCapable}, while * normal {@code BeanFactory} implementations are not. * @param registry the {@code BeanFactory} to load bean definitions into, in the form * of a {@code BeanDefinitionRegistry} * @param useDefaultFilters whether to include the default filters for the * {@link org.springframework.stereotype.Component @Component}, * {@link org.springframework.stereotype.Repository @Repository}, * {@link org.springframework.stereotype.Service @Service}, and * {@link org.springframework.stereotype.Controller @Controller} stereotype annotations * @see #setResourceLoader * @see #setEnvironment */ public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) { this(registry, useDefaultFilters, getOrCreateEnvironment(registry)); }
8.1、org.springframework.context.annotation.ClassPathBeanDefinitionScanner.getOrCreateEnvironment(BeanDefinitionRegistry)
/** * Get the Environment from the given registry if possible, otherwise return a new * StandardEnvironment. */ private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); if (registry instanceof EnvironmentCapable) { return ((EnvironmentCapable) registry).getEnvironment(); } return new StandardEnvironment(); }
9、org.springframework.context.annotation.ClassPathBeanDefinitionScanner.ClassPathBeanDefinitionScanner(BeanDefinitionRegistry, boolean, Environment)
/** * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and * using the given {@link Environment} when evaluating bean definition profile metadata. * <p>If the passed-in bean factory does not only implement the {@code * BeanDefinitionRegistry} interface but also the {@link ResourceLoader} interface, it * will be used as default {@code ResourceLoader} as well. This will usually be the * case for {@link org.springframework.context.ApplicationContext} implementations. * <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader} * will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}. * @param registry the {@code BeanFactory} to load bean definitions into, in the form * of a {@code BeanDefinitionRegistry} * @param useDefaultFilters whether to include the default filters for the * {@link org.springframework.stereotype.Component @Component}, * {@link org.springframework.stereotype.Repository @Repository}, * {@link org.springframework.stereotype.Service @Service}, and * {@link org.springframework.stereotype.Controller @Controller} stereotype annotations * @param environment the Spring {@link Environment} to use when evaluating bean * definition profile metadata * @since 3.1 * @see #setResourceLoader */ public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment) { this(registry, useDefaultFilters, environment, (registry instanceof ResourceLoader ? (ResourceLoader) registry : null)); }
10、org.springframework.context.annotation.ClassPathBeanDefinitionScanner.ClassPathBeanDefinitionScanner(BeanDefinitionRegistry, boolean, Environment, ResourceLoader)
/** * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and * using the given {@link Environment} when evaluating bean definition profile metadata. * @param registry the {@code BeanFactory} to load bean definitions into, in the form * of a {@code BeanDefinitionRegistry} * @param useDefaultFilters whether to include the default filters for the * {@link org.springframework.stereotype.Component @Component}, * {@link org.springframework.stereotype.Repository @Repository}, * {@link org.springframework.stereotype.Service @Service}, and * {@link org.springframework.stereotype.Controller @Controller} stereotype annotations * @param environment the Spring {@link Environment} to use when evaluating bean * definition profile metadata * @param resourceLoader the {@link ResourceLoader} to use * @since 4.3.6 */ public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment, ResourceLoader resourceLoader) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); this.registry = registry; if (useDefaultFilters) { registerDefaultFilters(); } setEnvironment(environment); setResourceLoader(resourceLoader); }
10.1、org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.registerDefaultFilters()
/** * Register the default filter for {@link Component @Component}. * <p>This will implicitly register all annotations that have the * {@link Component @Component} meta-annotation including the * {@link Repository @Repository}, {@link Service @Service}, and * {@link Controller @Controller} stereotype annotations. * <p>Also supports Java EE 6's {@link javax.annotation.ManagedBean} and * JSR-330's {@link javax.inject.Named} annotations, if available. * */ //为容器中的组件注册默认的过滤器 //这将隐式的注册所有标(@Component、@Repository、@Service、@Controller)的注解 //如果可用,还支持Java EE 6的{@link javax.annotation.ManagedBean}和JSR-330的{@link javax.inject.Named}注解。 @SuppressWarnings("unchecked") protected void registerDefaultFilters() { this.includeFilters.add(new AnnotationTypeFilter(Component.class)); ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader(); try { this.includeFilters.add(new AnnotationTypeFilter( ((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false)); logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning"); } catch (ClassNotFoundException ex) { // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip. } try { this.includeFilters.add(new AnnotationTypeFilter( ((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false)); logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning"); } catch (ClassNotFoundException ex) { // JSR-330 API not available - simply skip. } }
11、org.springframework.context.annotation.AnnotationConfigApplicationContext.register(Class<?>...)
/** * Register one or more annotated classes to be processed. * <p>Note that {@link #refresh()} must be called in order for the context * to fully process the new classes. * @param annotatedClasses one or more annotated classes, * e.g. {@link Configuration @Configuration} classes * @see #scan(String...) * @see #refresh() */ //注册一个或多个要处理的带注解的类。 //注意,必须调用#refresh方法,以使上下文完全处理新类。 public void register(Class<?>... annotatedClasses) { Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified"); this.reader.register(annotatedClasses); }
12、org.springframework.context.annotation.AnnotatedBeanDefinitionReader.register(Class<?>...)
/** * Register one or more annotated classes to be processed. * <p>Calls to {@code register} are idempotent; adding the same * annotated class more than once has no additional effect. * @param annotatedClasses one or more annotated classes, * e.g. {@link Configuration @Configuration} classes */ //注册一个或多个要处理的带注解的类。 //对#register的调用是幂等的; 多次添加标有同样注解的类不会产生任何其他影响。 public void register(Class<?>... annotatedClasses) { for (Class<?> annotatedClass : annotatedClasses) { registerBean(annotatedClass); } }
13、org.springframework.context.annotation.AnnotatedBeanDefinitionReader.registerBean(Class<?>)
/** * Register a bean from the given bean class, deriving its metadata from * class-declared annotations. * @param annotatedClass the class of the bean */ //从给定的bean类中注册bean,并从类声明注解中派生其元数据。 @SuppressWarnings("unchecked") public void registerBean(Class<?> annotatedClass) { registerBean(annotatedClass, null, (Class<? extends Annotation>[]) null); }
14、org.springframework.context.annotation.AnnotatedBeanDefinitionReader.registerBean(Class<?>, String, Class<? extends Annotation>...)
/** * Register a bean from the given bean class, deriving its metadata from * class-declared annotations. * @param annotatedClass the class of the bean * @param name an explicit name for the bean * @param qualifiers specific qualifier annotations to consider, * in addition to qualifiers at the bean class level */ @SuppressWarnings("unchecked") public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) { AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass); if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) { return; } ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); abd.setScope(scopeMetadata.getScopeName()); String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); AnnotationConfigUtils.processCommonDefinitionAnnotations(abd); 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)); } } } BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); }
14.1、org.springframework.context.annotation.AnnotationConfigUtils.processCommonDefinitionAnnotations(AnnotatedBeanDefinition)
public static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd) { processCommonDefinitionAnnotations(abd, abd.getMetadata()); } static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) { if (metadata.isAnnotated(Lazy.class.getName())) { abd.setLazyInit(attributesFor(metadata, Lazy.class).getBoolean("value")); } else if (abd.getMetadata() != metadata && abd.getMetadata().isAnnotated(Lazy.class.getName())) { abd.setLazyInit(attributesFor(abd.getMetadata(), Lazy.class).getBoolean("value")); } if (metadata.isAnnotated(Primary.class.getName())) { abd.setPrimary(true); } if (metadata.isAnnotated(DependsOn.class.getName())) { abd.setDependsOn(attributesFor(metadata, DependsOn.class).getStringArray("value")); } if (abd instanceof AbstractBeanDefinition) { AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd; if (metadata.isAnnotated(Role.class.getName())) { absBd.setRole(attributesFor(metadata, Role.class).getNumber("value").intValue()); } if (metadata.isAnnotated(Description.class.getName())) { absBd.setDescription(attributesFor(metadata, Description.class).getString("value")); } } }