视频地址:点击跳转
如何快速大家一个spring容器:
- 导入spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
- 初始化Spring环境(有三种方式,我们这里讲的是基于注解的方式,还有ClassPathXmlApplicationContext通过xml文件启动等)
public class Client {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Appconfig.class);
TestBean tb = (TestBean) context.getBean("testBean");
tb.sayHello();
}
}
Appconfig.class(@ComponentScan(“com.hdl”) 告诉spring扫描"com.hdl"包下所有的带有@Component的类就说明是需要交给spring管理的类)
@ComponentScan("com.hdl")
@Configuration
public class Appconfig{ //自动扫描这个类,然后扫描上面注解后的类
public TestConfiguration() {
System.out.println("TestConfiguration容器初始化...");
}
}
- 创建对象类
@component
public class TestBean {
private String username;
private String url;
private String password;
public void sayHello() {
System.out.println("TestBean sayHello...");
}
public String toString() {
return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
}
public void start() {
System.out.println("TestBean 初始化。。。");
}
public void cleanUp() {
System.out.println("TestBean 销毁。。。");
}
}
- 执行main方法,环境搭建完成
spring容器到底是如何初始化的呢?
其实只有一条语句: ApplicationContext context = new AnnotationConfigApplicationContext(Appconfig.class);
我们进AnnotationConfigApplicationContext的构造方法中看看
- 首先是this(),调用无参构造方法,我们要知道这个类是有父类的(GenericApplicationContext),所以执行this()前,会去调用父类的无参构造方法,父类构造器的内容如下,也就是初始化了一个beanFactory
自己的无参方法this()没有什么内容,我们就不看了 - 接着向下执行,我们先跳过register(annotatedClasses),直接先看 refresh()方法,点到refresh()方法中,会发现这个方法中调用了大概十个函数(如下),我们先讲其中的invokeBeanFactoryPostProcessors(beanFac