赞
踩
目录
真是万事开头难,一点不假。计划着写一个spring源码分析的系列文章,但是每每提笔又不知道该用什么样的开场白比较合适,很是无奈。实话讲,阅读源码的过程很漫长甚至有点痛苦,但是每次学到些什么又会有莫名的满足,从这篇文章开始,我们一点点一步步来揭开spring源码的神秘面纱,我们切勿急躁,怀着一颗虔诚的心踏踏实实的学,就像是流水不争先只争个滔滔不绝。
闲言少叙,言归正传。spring启动流程我准备分为上中下三篇,本篇重点内容包括配置类转beanDefinition并注册到spring容器的过程,ConfigurationClassPostProcessor这个最重要的后置处理器的注册过程。注意哦,本篇内容只会介绍它的注册过程具体解析过程在下一篇。
(1) 通过包扫描交给spring托管的IndexDao类:
- @Component
- public class IndexDao {
- public void query(){
- System.out.println("indexDao query...");
- }
- }
(2) 通过@Import交给spring托管的IndexDao2类:
- public class IndexDao2 {
- public void query(){
- System.out.println("indexDao2 query...");
- }
- }
(3) 核心配置类IocConfig:
- @Configuration
- @ComponentScan("com.zlb.ioc")
- @Import(MySelector.class)
- public class IocConfig {
-
- }
(4) MySelector类,重写方法返回的正式IndexDao2的全限定名:
- public class MySelector implements ImportSelector {
- @Override
- public String[] selectImports(AnnotationMetadata importingClassMetadata) {
- return new String[]{IndexDao2.class.getName()};
- }
- }
(5) 最后,主测试类:
- public class Demo {
- public static void main(String[] args) {
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IocConfig.class);
- IndexDao dao = context.getBean(IndexDao.class);
- IndexDao2 dao2 = context.getBean(IndexDao2.class);
- dao.query();
- dao2.query();
- }
- }
进入到创建上下文对象的构造方法中:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IocConfig.class);
- public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
- this();
- register(componentClasses);
- refresh();
- }
这里我们要注意一下,在执行this方法之前java会首先执行父类的无参构造,就是
GenericApplicationContext的GenericApplicationContext()方法:
- public GenericApplicationContext() {
- this.beanFactory = new DefaultListableBeanFactory();
- }
注:我们常说的bean工厂正是上边这个货DefaultListableBeanFactory,它也是我们spring上下文对象的一个属性。
接下来我们再进入到this方法:
- public AnnotationConfigApplicationContext() {
- StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
- //这个构造函数主要做了两件事
- // 1.AnnotatedBeanDefinitionReader的registry赋值
- // 2.向beanFactory中注册ConfigurationClassPostProcessor
- // 进到这行
- this.reader = new AnnotatedBeanDefinitionReader(this);
- createAnnotatedBeanDefReader.end();
- this.scanner = new ClassPathBeanDefinitionScanner(this);
- }
- public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
- //进到这行
- this(registry, getOrCreateEnvironment(registry));
- }
- public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
- Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
- Assert.notNull(environment, "Environment must not be null");
- //给registry属性赋值 后边注册自定义Config类的时候会用到
- this.registry = registry;
- this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
- //向beanFactory中注册ConfigurationClassPostProcessor 进入这个方法
- AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
- }
- public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
- //进到这个方法
- registerAnnotationConfigProcessors(registry, null);
- }
- public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
- BeanDefinitionRegistry registry, @Nullable Object source) {
-
- //从registry(上下文)中获取beanFactory
- DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
- //给beanFactory设置两个属性 暂时不用管
- 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<>(8);
-
- //向beanFactory中注册ConfigurationClassPostProcessor
- //这个if块最重要其他不用管
- if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
- //将ConfigurationClassPostProcessor转换成beanDefinition
- RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
- def.setSource(source);
- //registerPostProcessor()这个方法中注册ConfigurationClassPostProcessor
- //进到registerPostProcessor这个方法
- beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
- }
-
- 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));
- }
-
- // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
- 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.
- 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));
- }
-
- 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;
- }
- private static BeanDefinitionHolder registerPostProcessor(
- BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
-
- definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
- // 这个方法就是在注册了
- // registry就是我们的bean工厂DefaultListableBeanFactory
- // beanName就是org.springframework.context.annotation.internalConfigurationAnnotationProcessor
- // definition就是根据ConfigurationClassPostProcessor转换来的beanDefinition
- // 那到底注册是干啥呢 我们继续
- registry.registerBeanDefinition(beanName, definition);
- return new BeanDefinitionHolder(definition, beanName);
- }
注:注意哦,registry默认实现是DefaultListableBeanFactory,我们要进入到这个实现类的registerBeanDefinition()方法。
- @Override
- public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
- throws BeanDefinitionStoreException {
-
- Assert.hasText(beanName, "Bean name must not be empty");
- Assert.notNull(beanDefinition, "BeanDefinition must not be null");
-
- //校验 不用管
- if (beanDefinition instanceof AbstractBeanDefinition) {
- try {
- ((AbstractBeanDefinition) beanDefinition).validate();
- }
- catch (BeanDefinitionValidationException ex) {
- throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
- "Validation of bean definition failed", ex);
- }
- }
-
- BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
- //existingDefinition = null 不会进这个if
- if (existingDefinition != null) {
- if (!isAllowBeanDefinitionOverriding()) {
- throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
- }
- else if (existingDefinition.getRole() < beanDefinition.getRole()) {
- // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
- if (logger.isInfoEnabled()) {
- logger.info("Overriding user-defined bean definition for bean '" + beanName +
- "' with a framework-generated bean definition: replacing [" +
- existingDefinition + "] with [" + beanDefinition + "]");
- }
- }
- else if (!beanDefinition.equals(existingDefinition)) {
- if (logger.isDebugEnabled()) {
- logger.debug("Overriding bean definition for bean '" + beanName +
- "' with a different definition: replacing [" + existingDefinition +
- "] with [" + beanDefinition + "]");
- }
- }
- else {
- if (logger.isTraceEnabled()) {
- logger.trace("Overriding bean definition for bean '" + beanName +
- "' with an equivalent definition: replacing [" + existingDefinition +
- "] with [" + beanDefinition + "]");
- }
- }
- this.beanDefinitionMap.put(beanName, beanDefinition);
- }
- else {
- //不会进这个if
- if (hasBeanCreationStarted()) {
- // Cannot modify startup-time collection elements anymore (for stable iteration)
- synchronized (this.beanDefinitionMap) {
- this.beanDefinitionMap.put(beanName, beanDefinition);
- List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
- updatedDefinitions.addAll(this.beanDefinitionNames);
- updatedDefinitions.add(beanName);
- this.beanDefinitionNames = updatedDefinitions;
- removeManualSingletonName(beanName);
- }
- }
- else {
- // Still in startup registration phase
- //核心部分:注册beanDefinition
- //其实就是向bean工厂的beanDefinitionMap中put个beanDefinition
- //还有就是向bean工厂的beanDefinitionNames集合中添加一个名字而已
- this.beanDefinitionMap.put(beanName, beanDefinition);
- this.beanDefinitionNames.add(beanName);
- removeManualSingletonName(beanName);
- }
- this.frozenBeanDefinitionNames = null;
- }
-
- if (existingDefinition != null || containsSingleton(beanName)) {
- resetBeanDefinition(beanName);
- }
- else if (isConfigurationFrozen()) {
- clearByTypeCache();
- }
- }
那么行棋至此,this方法的主要逻辑我们已经看完了,小小总结一下this()方法究竟干了些啥呢?其实非常简单就干了两件事:
1. new了一个bean工厂的默认实现DefaultListableBeanFactory并赋值给了spring上下文的成员变量。
2. new了一个AnnotatedBeanDefinitionReader对象也赋值给了spring上下文的成员变量。但是这个不太重要。
3. 在new AnnotatedBeanDefinitionReader对象过程中向bean工厂中注册了一个特别重要的类ConfigurationClassPostProcessor,这个类极其极其重要!具体作用我们后面会说到,先请大家牢记此类。
接下来我们分析register()方法。这个方法很简单只做了一件事,那就是把我们的配置类注册给spring。
- public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
- this();
- //进到这个方法
- register(componentClasses);
- refresh();
- }
- @Override
- public void register(Class<?>... componentClasses) {
- Assert.notEmpty(componentClasses, "At least one component class must be specified");
- StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
- .tag("classes", () -> Arrays.toString(componentClasses));
- //参数componentClasses其实就是我们的配置类
- //进到这行
- this.reader.register(componentClasses);
- registerComponentClass.end();
- }
- public void register(Class<?>... componentClasses) {
- for (Class<?> componentClass : componentClasses) {
- //配置类可以传多个 但是我们只有一个 go on
- registerBean(componentClass);
- }
- }
- public void registerBean(Class<?> beanClass) {
- //继续
- doRegisterBean(beanClass, null, null, null, null);
- }
- private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
- @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
- @Nullable BeanDefinitionCustomizer[] customizers) {
- //把我们的配置类转成beanDefinition
- AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
- if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
- return;
- }
-
- abd.setInstanceSupplier(supplier);
- 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));
- }
- }
- }
- if (customizers != null) {
- for (BeanDefinitionCustomizer customizer : customizers) {
- customizer.customize(abd);
- }
- }
- //对beanDefinition和beanName再做一次封装 包装成一个holder
- BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
- definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
- //注册beanDefinition正是在这儿完成的 进去这行代码
- BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
- }
- public static void registerBeanDefinition(
- BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
- throws BeanDefinitionStoreException {
-
- // Register bean definition under primary name.
- String beanName = definitionHolder.getBeanName();
- //注册beanDefinition在这儿
- //registry默认实现是DefaultListableBeanFactory
- registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
-
- // Register aliases for bean name, if any.
- String[] aliases = definitionHolder.getAliases();
- if (aliases != null) {
- for (String alias : aliases) {
- registry.registerAlias(beanName, alias);
- }
- }
- }
- @Override
- public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
- throws BeanDefinitionStoreException {
-
- Assert.hasText(beanName, "Bean name must not be empty");
- Assert.notNull(beanDefinition, "BeanDefinition must not be null");
-
- //校验 不用管
- if (beanDefinition instanceof AbstractBeanDefinition) {
- try {
- ((AbstractBeanDefinition) beanDefinition).validate();
- }
- catch (BeanDefinitionValidationException ex) {
- throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
- "Validation of bean definition failed", ex);
- }
- }
-
- BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
- //existingDefinition = null 不会进这个if
- if (existingDefinition != null) {
- if (!isAllowBeanDefinitionOverriding()) {
- throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
- }
- else if (existingDefinition.getRole() < beanDefinition.getRole()) {
- // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
- if (logger.isInfoEnabled()) {
- logger.info("Overriding user-defined bean definition for bean '" + beanName +
- "' with a framework-generated bean definition: replacing [" +
- existingDefinition + "] with [" + beanDefinition + "]");
- }
- }
- else if (!beanDefinition.equals(existingDefinition)) {
- if (logger.isDebugEnabled()) {
- logger.debug("Overriding bean definition for bean '" + beanName +
- "' with a different definition: replacing [" + existingDefinition +
- "] with [" + beanDefinition + "]");
- }
- }
- else {
- if (logger.isTraceEnabled()) {
- logger.trace("Overriding bean definition for bean '" + beanName +
- "' with an equivalent definition: replacing [" + existingDefinition +
- "] with [" + beanDefinition + "]");
- }
- }
- this.beanDefinitionMap.put(beanName, beanDefinition);
- }
- else {
- //不会进这个if
- if (hasBeanCreationStarted()) {
- // Cannot modify startup-time collection elements anymore (for stable iteration)
- synchronized (this.beanDefinitionMap) {
- this.beanDefinitionMap.put(beanName, beanDefinition);
- List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
- updatedDefinitions.addAll(this.beanDefinitionNames);
- updatedDefinitions.add(beanName);
- this.beanDefinitionNames = updatedDefinitions;
- removeManualSingletonName(beanName);
- }
- }
- else {
- // Still in startup registration phase
- //核心部分:注册beanDefinition
- //其实就是向bean工厂的beanDefinitionMap中put个beanDefinition
- //还有就是向bean工厂的beanDefinitionNames集合中添加一个名字而已
- this.beanDefinitionMap.put(beanName, beanDefinition);
- this.beanDefinitionNames.add(beanName);
- removeManualSingletonName(beanName);
- }
- this.frozenBeanDefinitionNames = null;
- }
-
- if (existingDefinition != null || containsSingleton(beanName)) {
- resetBeanDefinition(beanName);
- }
- else if (isConfigurationFrozen()) {
- clearByTypeCache();
- }
- }
截止到这里,我们已经把配置类转换成了beanDefinition并且注册给了spring容器。再强调一次,所谓注册通俗点说就是把我们的类转换成beanDefinition然后放到beanFactory的集合里边,也就是这个:
this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。