1、Spring底层核心原理解析
1.入门案例
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserService userService = (UserService) context.getBean("userService");
userService.test();
对于这三行代码应该,大部分同学应该都是比较熟悉,这是学习Spring的hello world。可是,这三行代码底层都做了什么,比如:
- 第一行代码,会构造一个ClassPathXmlApplicationContext对象,ClassPathXmlApplicationContext该如何理解,调用该构造方法除开会实例化得到一个对象,还会做哪些事情?
- 第二行代码,会调用ClassPathXmlApplicationContext的getBean方法,会得到一个UserService对象,getBean()是如何实现的?返回的UserService对象和我们自己直接new的UserService对象有区别吗?
- 第三行代码,就是简单的调用UserService的test()方法,不难理解。
光看这三行代码,其实并不能体现出来Spring的强大之处,也不能理解为什么需要ClassPathXmlApplicationContext和getBean()方法。对于这三行代码,你现在可以认为:如果你要用Spring,你就得这么写。就像你要用Mybatis,你就得写各种Mapper接口。
但是用ClassPathXmlApplicationContext其实已经过时了,在新版的Spring MVC和Spring Boot的底层主要用的都是AnnotationConfigApplicationContext,比如:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
UserService userService = (UserService) context.getBean("userService");
userService.test();
可以看到AnnotationConfigApplicationContext的用法和ClassPathXmlApplicationContext是非常类似的,只不过需要传入的是一个class,而不是一个xml文件。
而AppConfig.class和spring.xml一样,表示Spring的配置,比如可以指定扫描路径,可以直接定义Bean,比如:
spring.xml中的内容为:
<context:component-scan base-package="com.zhouyu"/>
<bean id="userService" class="com.zhouyu.service.UserService"/>
AppConfig中的内容为:
@ComponentScan("com.zhouyu")
public class AppConfig {@Beanpublic UserService userService(){return new UserService();}}
所以spring.xml和AppConfig.class本质上是一样的。
目前,我们基本很少直接使用上面这种方式来用Spring,而是使用Spring MVC,或者Spring Boot,但是它们都