【Spring】之 启动Spring


一、问题


(1) main方法 如何启动 Spring ?

常见的如:

ApplicationContext ctx = new XmlApplicationContext("app.xml");

但有自从有了自动装配后:

  1. Spring自动装配方式
  2. SpringBoot自动装配方式

1. Spring 自动装配方式

版本: 5.0.7.RELEASE
方式: 注解

启动类

@ComponentScan(basePackages = "com.donaldy")
public class Application {

    public static void main(String[] args) {

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Application.class);

        Car car = (Car) applicationContext.getBean("car");

        System.out.println(car);

        Teacher teacher = applicationContext.getBean(Teacher.class);

        System.out.println(teacher.toString());
    }
}

封装成 Bean:

package com.donaldy.bean;

import org.springframework.stereotype.Component;

@Component
public class Teacher {

    private String name;

    private int age;

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + "yyf" + '\'' +
                ", age=" + 24 +
                '}';
    }
}

封装成 Bean 2:

package com.donaldy.bean;

import org.springframework.stereotype.Component;

@Component
public class Car {

    private String brand = "宝马";

    private String color = "红色";

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", color='" + color + '\'' +
                '}';
    }
}

2. SpringBoot自动装配

版本: 2.0.3.RELEASE
方式: 注解

启动类

@SpringBootApplication
public class LearnApplication {
	
	public static void main(String[] args) {

		ConfigurableApplicationContext context = new SpringApplicationBuilder(LearnApplication.class)
				.web(WebApplicationType.NONE)
				.run(args);

		UserService userService = context.getBean(UserService.class);

		System.out.println("UserService Bean: " + userService);

		// 关闭上下文
		context.close();
	}
}

Bean:

public interface UserService {
}

@Service
public class UserServiceImpl implements UserService {
}

(2) Web 容器中如何启动 Spring ?

什么是 Web容器(Servlet 容器)?
对请求进行响应
例如:Tomcat、Jetty、Jboss等


1. Spring 自带的Servlet

利用 Spring 自带的 Servlet启动, 配好Servlet, 加载Servlet的时候, 就初始化了WebApplicationContext

如图:

在这里插入图片描述


2. Spring 自带的Listener

利用 Spring 自带的 Listener启动, 配好Listener, 加载Listenser的时候, 就初始化了WebApplicationContext

如图:

在这里插入图片描述


(3) Spring 创建过程是怎样的 ?

先看下这个:

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
    this();
    register(annotatedClasses);
    refresh();
}

可以看出主要三件事:

  1. 创建环境(为创建Bean提供环境)
  2. 扫描需要创建Bean
  3. 创建Bean

简略如图:
在这里插入图片描述

发布了404 篇原创文章 · 获赞 270 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/fanfan4569/article/details/101927028