常见的如:
ApplicationContext ctx = new XmlApplicationContext("app.xml");但有自从有了自动装配后:
Spring自动装配方式SpringBoot自动装配方式版本: 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.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 { }什么是 Web容器(Servlet 容器)? 对请求进行响应 例如:Tomcat、Jetty、Jboss等
利用 Spring 自带的 Servlet启动, 配好Servlet, 加载Servlet的时候, 就初始化了WebApplicationContext
如图:
利用 Spring 自带的 Listener启动, 配好Listener, 加载Listenser的时候, 就初始化了WebApplicationContext
如图:
先看下这个:
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { this(); register(annotatedClasses); refresh(); }可以看出主要三件事:
创建环境(为创建Bean提供环境)扫描需要创建Bean创建Bean简略如图: