ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml")调试收获

本文详细探讨了`ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml")`在Spring框架中的执行流程,包括构造方法调用、Bean的实例化、BeanPostProcessor注册、Aware接口处理以及初始化方法的执行。在refresh()方法中,关键步骤如BeanFactory的获取、监听器注册、Bean的初始化等过程被逐一解析。
摘要由CSDN通过智能技术生成

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml")代码调试收获



1.通过super(parent)调用了父类AbstractApplicationContext的构造方法,使AbstractApplicationContext中

ResourcePatternResolver resourcePatternResolver=new PathMatchingResourcePatternResolver;引发学习http://cainiaoboke.iteye.com/blog/2327685

 

2.setConfigLocations(configLocations)调用父类AbstractRefreshableConfigApplicationContext的setConfigLocations方法,使中的private String[] configLocations=[Beans.xml]

 

3.重点refresh开始调用AbstractApplicationContext的refresh()方法

public void refresh() throws BeansException, IllegalStateException {  
        synchronized (this.startupShutdownMonitor) {  
            // 容器启动的预先准备,记录容器启动的时间和标记  
            prepareRefresh();  
  
            // 创建BeanFactory,如果已有就销毁,没有就创建。此类实现了对BeanDefinition的装载  
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();  
  
            // 配置BeanFactory标准上下文特性,如类装载器,PostProcesser等  
            prepareBeanFactory(beanFactory);  
  
            try {  
                // 在bean被装载后,提供一个修改BeanFactory的入口  
                postProcessBeanFactory(beanFactory);  
  
                // 调用postProcessBeanFactory  
                invokeBeanFactoryPostProcessors(beanFactory);  
  
                // 注册用于拦截bean创建过程中的BeanPostProcessors  
                registerBeanPostProcessors(beanFactory);  
  
                // Initialize message source for this context.  
                initMessageSource();  
  
                // Initialize event multicaster for this context.  
                initApplicationEventMulticaster();  
  
                // Initialize other special beans in specific context subclasses.  
                onRefresh();  
  
                // 注册监听器  
                registerListeners();  
  
                // 完成容器的初始化,里面的preInstantiateSingletons()完成对单例对象的创建  
                finishBeanFactoryInitialization(beanFactory);  
  
                // Last step: publish corresponding event.  
                finishRefresh();  
            }  
  
            catch (BeansException ex) {  
                // Destroy already created singletons to avoid dangling resources.  
                beanFactory.destroySingletons();  
  
                // Reset 'active' flag.  
                cancelRefresh(ex);  
  
                // Propagate exception to caller.  
                throw ex;  
            }  
        }  
    }  

 

 

容器启动的预先准备,记录容器启动的时间和标记  初始化PropertySources校验需要的properties
protected void prepareRefresh() {
		this.startupDate = System.currentTimeMillis();

		synchronized (this.activeMonitor) {
			this.active = true;
		}

		if (logger.isInfoEnabled()) {
			logger.info("Refreshing " + this);
		}

		// Initialize any placeholder property sources in the context environment
		initPropertySources();

		// Validate that all properties marked as required are resolvable
		// see ConfigurablePropertyResolver#setRequiredProperties
		getEnvironment().validateRequiredProperties();
	}

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();   

1. 加载XML文件,封装成Resource对象

2. 调用Reader对象方法读取XML文件内容,并将相关属性放到BeanDefinition实例
3. 将BeanDefinition对象放到BeanFactory对象

 

对于默认的单例Bean在refresh中的

// Instantiate all remaining (non-lazy-init) singletons.

finishBeanFactoryInitialization(beanFactory); 中实例化

 

 对于非单例或延迟加载的Bean在refresh中的实例化在getbean方法时实例化

BeanPostProcessor的构造方法的调用都在refresh()中的

// Register bean processors that intercept bean creation.

 

registerBeanPostProcessors(beanFactory);

要点:

refresh()中initApplicationEventMulticaster();注册监听

registerBeanPostProcessors(beanFactory);注册BeanPostProcessor

这是BeanPostProcessor实现类构造器!!  BeanPostProcessor在这里创建实例

finishRefresh();发送事件给刚注册的监听

finishBeanFactoryInitialization(beanFactory);里面是创建对象 属性赋值等,如下:

 

Hello World构造函数被调用了

setMessage 被调用了

EnvironmentAware 被调用了

ApplicationContextAware 被调用了

bean处理器:bean创建之前..

InitializingBean afterPropertiesSet 被调用了

int-method 被调用了

bean处理器:bean创建之后..

ApplicationListener 被调用了 (创建容器)

ApplicationListener 被调用了  (销毁容器)

DisposableBean 被调用了

destroy-method 被调用了

 具体实现在AbstractAutowireCapableBeanFactory里



 populateBean(beanName, mbd, instanceWrapper);里面是属性赋值,依赖注入

 exposedObject = initializeBean(beanName, exposedObject, mbd);里面是:

EnvironmentAware 被调用了

ApplicationContextAware 被调用了

bean处理器:bean创建之前..

InitializingBean afterPropertiesSet 被调用了

int-method 被调用了

bean处理器:bean创建之后..

 exposedObject = initializeBean(beanName, exposedObject, mbd);中有段代码:

①if (mbd == null || !mbd.isSynthetic()) {

wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

}

这个就是处理BeanPostProcessor的,Aware接口的实现了,是因为在refresh中

prepareBeanFactory(beanFactory);里面添加了一个beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

所以说常用的aware接口方式是:在BeanPostProcessor中默认都加了一个ApplicationContextAwareProcessor,而这个ApplicationContextAwareProcessor实现了BeanPostProcessor接口,所以在加载后置处理器时就处理aware相关的逻辑

invokeInitMethods(beanName, wrappedBean, mbd);

这个加载实现了先后加载InitializingBean 和有init-method方法

③wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

这个方法加载BeanPostProcessor的 postProcessAfterInitialization方法

 

 

 

 



 

package com.jhuc.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

public class HelloWorld implements ApplicationContextAware,EnvironmentAware,InitializingBean,ApplicationListener,DisposableBean{
    private String message;
    public HelloWorld(){
        System.out.println("Hello World构造函数被调用了");
    }

    public void setMessage(String message){
        System.out.println("setMessage 被调用了");
        this.message  = message;
    }
 
    public String getMessage(){
        return this.message;
    }
 
    
    public void byebye(){
           System.out.println("int-method 被调用了");
    }

    @Override
    public void setEnvironment(Environment environment) {
        System.out.println("EnvironmentAware 被调用了");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("ApplicationContextAware 被调用了");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean afterPropertiesSet 被调用了");
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("ApplicationListener 被调用了");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean 被调用了");
    }
    public void destroyMethod(){
        System.out.println("destroy-method 被调用了");
    }
}

 

package com.jhuc.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {
 
     public MyBeanPostProcessor() {
        super();
        System.out.println("这是BeanPostProcessor实现类构造器!!");        
     }
 
     @Override
     public Object postProcessAfterInitialization(Object bean, String arg1)
             throws BeansException {
         System.out.println("bean处理器:bean创建之后..");
         return bean;
     }
 
     @Override
     public Object postProcessBeforeInitialization(Object bean, String arg1)
             throws BeansException {
         System.out.println("bean处理器:bean创建之前..");
     
         return bean;
     }
 }

 

package org.example; public interface StudentDao { void list(); void delete(int id); } package org.example; public interface StudentService { void list(); void delete(int id); } package org.example; import org.springframework.stereotype.Repository; @Repository("mockStudentDao") public class MockStudentDao implements StudentDao{ @Override public void list() { System.out.println("All students are listed in MockStudentDao."); } @Override public void delete(int id) { System.out.println("Student No."+id+"is deleted in MockStudentDao."); } } package org.example; import org.springframework.stereotype.Repository; @Repository("myBatisStudentDao") public class MyBatisStudentDao implements StudentDao{ @Override public void list() { System.out.println("All students are listed in MyBatisStudentDao."); } @Override public void delete(int id) { System.out.println("Student No."+id+"is deleted in MyBatisStudentDao."); } } package org.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service("studentServiceImpl") public class StudentServiceImpl implements StudentService{ private final StudentDao studentDao; @Autowired public StudentServiceImpl(@Qualifier("myBatisStudentDao")StudentDao studentDao){ this.studentDao=studentDao; } @Override public void list() { this.studentDao.list(); } @Override public void delete(int id) { this.studentDao.delete(id); } } package org.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); StudentService studentService = (StudentService) ctx.getBean("studentServiceImpl"); studentService.list(); studentService.delete(10); } }
最新发布
05-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值