剑指Java自研框架,决胜Spring源码

  --------------------

  下栽の地止:https://www.itwangzi.cn/2378.html

  --------------------

  剑指Java自研框架,决胜Spring源码

  讲解Spring之前,我们首先梳理下Spring有哪些知识点可以进行入手源码分析,比如:

  1.Spring IOC依赖注入2.Spring AOP切面编程3.Spring Bean的声明周期底层原理4.Spring 初始化底层原理5.Spring Transaction事务底层原理

  通过这些知识点,后续我们慢慢在深入Spring的使用及原理剖析,为了更好地理解Spring,我们需要先了解一个最简单的示例——Hello World。在学习任何框架和语言之前,Hello World都是必不可少的。

  //在以前大家都是spring.xml进行注入bean后供Spring框架解析ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");UserService userService = (UserService) context.getBean("userService");userService.test();

  spring.xml中的内容为:

  <context:component-scan base-package="com.zhouyu"/><bean id="userService" class="com.zhouyu.service.UserService"/>

  如果对上面的代码或者xml形式很陌生,再看下面一种代码,也是目前流行的一种形式

  //通过我们的配置类进行注入bean并解析AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MySpringConfig.class);//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");UserService userService = (UserService) context.getBean("userService");userService.test()

  MySpringConfig中的内容为:

  @ComponentScan("com.xiaoyu")public class MySpringConfig { @Bean public UserService userService(){ return new UserService(); }}

  相信很多人都会对上面的代码不陌生,那我们来看下这三行代码都做了那些工作:

  1.构造一个ClassPathXmlApplicationContext类解析配置文件 或者AnnotationConfigApplicationContext类 解析配置类,那么调用该构造方法除开会实例化得到一个对象,还会做哪些事情?2.从context中获取一个名字为"userService"的userService对象,那么为什么输入一个字符串就可以得到对象呢,好像跟Map<String,Object>有些类似,getBean()又是如何实现的?返回的UserService对象和我们自己直接new的UserService对象有区别吗?3.通过获取到的UserService对象调用test方法,这个不难理解。

  虽然我们目前很少直接使用这种方式来使用Spring,而是使用Spring MVC或者Spring Boot,但是它们都是基于上面这种方式的,都需要在内部去创建一个 ApplicationContext的,只不过:

  1.Spring MVC创建的是XmlWebApplicationContext,和ClassPathXmlApplicationContext类似,都是基于XML配置的2.Spring Boot创建的是AnnotationConfigApplicationContext

  根据上面这三步我们大概找到了进行源码深入的方向,本章只是简单讲解下如何简单使用Spring,先对这些流程有个印象,并带着疑惑来进一步探究Spring的内部机制。

  举报/反馈