【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

簡略如圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章