zoukankan      html  css  js  c++  java
  • 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 构造过程):

  • 相关阅读:
    ES6关于Promise的用法
    JS进阶篇--JS数组reduce()方法详解及高级技巧
    JavaScript常用数组操作方法,包含ES6方法
    揭密 Vue 的双向绑定
    JavaScript(E5,6) 正则学习总结学习,可看可不看!
    利用scons构建project
    cuda核函数再调用核函数,多层并行
    使用微信JSSDK实现图片上传
    android 自己定义水平和圆形progressbar 仅仅定义一些style就能够
    [LeetCode] 035. Search Insert Position (Medium) (C++)
  • 原文地址:https://www.cnblogs.com/wykCN/p/14033416.html
Copyright © 2011-2022 走看看