文章目錄
一、問題
(1) main
方法 如何啓動 Spring
?
常見的如:
ApplicationContext ctx = new XmlApplicationContext("app.xml");
但有自從有了自動裝配後:
Spring
自動裝配方式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();
}
可以看出主要三件事:
- 創建環境(爲創建Bean提供環境)
- 掃描需要創建Bean
- 創建Bean
簡略如圖: