文章目录
- 一. 创建 Spring 项目
- 1.1 创建一个Maven项目
- 1.2 添加Spring依赖
- 1.4. 创建一个启动类
 
- 二. 将 Bean 对象存放至 Spring 容器中
- 三. 从 Spring 容器中读取到 Bean
- 1. 得到Spring对象
- 2. 通过Spring 对象getBean方法获取到 Bean对象【DI操作】
 
一. 创建 Spring 项目
接下来使⽤ Maven ⽅式来创建⼀个 Spring 项⽬,创建 Spring 项⽬和 Servlet 类似,总共分为以下 3步:
- 创建⼀个普通 Maven 项⽬。
- 添加 Spring 框架⽀持(spring-context、spring-beans)。
- 添加启动类。
1.1 创建一个Maven项目
此处使用的IDEA版本为2021.3.2.
 
 
 注意:项目名称中不能有中文.
 
1.2 添加Spring依赖
- 配置Maven国内源.
 IDEA设置文件有两个(一个是当前项目配置文件,新项目配置文件).需要设置这两个配置文件的国内源.
 当前项目配置文件:
  
  
  
 配置settings.xml至C:\Users\xxxflower\.m2中.
  
 使用VScode打开文件.
  
新项目的配置文件:
 
 方法同上设置新项目的配置文件.
- 重新下载jar包.(可无)
 清空删除本地所有的jar包.
  
  
  
- 添加Spring依赖
 在Maven中央仓库中搜索Spring,点击5.x.x版本复制到pom.xml中.重新reload
  
1.4. 创建一个启动类

二. 将 Bean 对象存放至 Spring 容器中
- 创建一个bean.(在Java中一个对象如果被使用多次,就可以称之为Bean)
  
- 将Bean存储到Spring容器中 
  
三. 从 Spring 容器中读取到 Bean
1. 得到Spring对象
想要从 Spring 中将Bean对象读取出来,先要得到 Spring 上下文对象,相当于得到了 Spring 容器。再通过 spring 上下文对象提供的方法获取到需要使用的Bean对象,最后就能使用Bean对象了。
 ApplicationContext,也称为控制反转(IoC)容器,是 Spring 框架的核心。
| 实现类 | 描述 | 
|---|---|
| ClassPathXmlApplicationContext(常用) | 加载类路径下的配置文件,要求配置文件必须在类路径下 | 
| FileSystemXmlApplicationContext | 可以加载磁盘任意路径下的配置文件(必须要有访问权限) | 
| AnnotationContigApplicationContext | 用于读取注解创建容器 | 
package demo;
public class Student {
    public Student() {
        System.out.println("Student 已加载!");
    }
    public void sayHi(String name) {
        System.out.println("Hello!" + name);
    }
}
package demo;
public class Teacher {
    public Teacher() {
        System.out.println("Teacher 已加载!");
    }
    public void sayHi(String name) {
        System.out.println("Hello!" + name );
    }
}

import demo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
    public static void main(String[] args) {
        //1.得到 Spring
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
}
运行结果:
 
 程序启动,ApplicationContext创建时,会将所有的Bean对象都构造,类似于饿汉的方式。
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class App2 {
    public static void main(String[] args) {
        // 1. 得到 bean 工厂
        BeanFactory factory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
    }
}
运行结果:
  程序启动,在
程序启动,在BeanFactory创建时,结果中没有如何输出,只要不去获取使用Bean就不会去加载,类似于懒汉的方式。
2. 通过Spring 对象getBean方法获取到 Bean对象【DI操作】
获取getBean的三种方式:
- 根据Bean的名字来获取
Student student = (Student) context.getBean("student");
此时返回的是一个Object对象,需要我们去进行强制类型转换。
- 根据Bean类型获取
Student student = context.getBean(Student.class);
这种方式当beans中只有一个类的实例没有问题,但是个有多个同类的实例,会有问题,即在 Spring 中注入多个同一个类的对象,就会报错。
 
 
 抛出了一个NoUniqueBeanDefinitionException异常,这表示注入的对象不是唯一的.
- 根据名称 + 类型获取
Student student = context.getBean("student",Student.class);
运行结果:
 
 相比方式1更好,也是较为常用的方法.



















