Spring启动流程分析

Spring启动流程分析

如何启动一个Spring容器

启动一个Spring容器最简单的方式如下:

@Configuration
@ComponentScan(basePackages = "cn.wyk.primary.spring.ioc")
public class App {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctc = new AnnotationConfigApplicationContext(App.class);
		PrimaryService primaryService = (PrimaryService)ctc.getBean("primaryService");
		System.out.println(primaryService);
	}
}

上述代码演示了使用AnnotationConfigApplicationContext对象启动Spring容器的一种方式,除此之外Spring还支持其他的几个启动类来启动Spring;

如:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringBean.xml");

或者通过文件路径的方式:

      String path = this.getClass().getClassLoader().getResource("").getPath();
      System.out.println("path = " + path);
      String filepath = path + "/applicationContext.xml";

      ApplicationContext ac = new FileSystemXmlApplicationContext(filepath); 
      Object bean = ac.getBean("fieldInfo");

甚至可以更灵活的方式:

GenericApplicationContext ctx = new GenericApplicationContext();
//使用XmlBeanDefinitionReader
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
//加载ClassPathResource
xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));
PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
propReader.loadBeanDefinitions(new ClassPathResource("otherBeans.properties"));
//调用Refresh方法
ctx.refresh();

//和其他ApplicationContext方法一样的使用方式
MyBean myBean = (MyBean) ctx.getBean("myBean");

Spring初始化过程中都干了啥

第一部分,我们了解了如何启动一个一个Spring容器,这一部分将会分析下Spring启动过程都干了什么
Spring Start
在new XXXApplicationContext()的方法里主要有三个操作

  • this()
  • register()
  • refresh()

先来看看this方法里面都做了些什么(AnnotationConfigApplicationContext 构造过程):

原文地址:https://www.cnblogs.com/wykCN/p/14033416.html