IoC:工厂模式
AOP:代理模式
IoC 是 Spring 框架的灵魂,控制反转。
开发步骤
1、创建 Maven ⼯程,pom.xml 导⼊依赖。
org.springframework spring-context 5.2.3.RELEASE
2、在 resources 路径下创建 spring.xml。
3、IoC 容器通过读取 spring.xml 配置⽂件,加载 bean 标签来创建对象。
4、调⽤ API 获取 IoC 容器中已经创建的对象。
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("spring.xml");
Student student = (Student)applicationContext.getBean("student");
System.out.println(student);
IoC 容器创建 bean 的两种方式
无参构造函数
给成员变量赋值
有参构造函数
从 IoC 容器中取 bean
通过 id 取值
Student student = (Student)applicationContext.getBean("student");
通过类型取值。
Student student = (Student)applicationContext.getBean(Student.class);
bean 的属性中如果包含特殊字符,如下处理即可
IoC DI]]>
DI 指 bean 之间的依赖注⼊,设置对象之间的级联关系。
Classes
@Data
public class Classes {
private Integer id;
private String name; }
Student
@Data
@NoArgsConstructor
public class Student {
private Integer id;
private String name;
private Integer age;
private Classes classes;
public Student(Integer id, String name, Integer age) {
System.out.println("通过有参构造创建对象");
this.id = id;
this.name = name;
this.age = age;
}
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
}
spring-di.xml
bean 之间的级联需要使⽤ ref 属性完成映射,⽽不能直接使⽤ value ,否则会抛出类型转换异常。
Classes
@Data
public class Classes {
private Integer id;
private String name;
private List studentList; }
spring.xml
Spring 中的 bean
bean 是根据 scope 来⽣成,表示 bean 的作⽤域,scope 有 4 种类型:
singleton,单例,表示通过 Spring 容器获取的对象是唯⼀的,默认值。
prototype,原型,表示通过 Spring 容器获取的对象是不同的。
request,请求,表示在⼀次 HTTP 请求内有效。
session,会话,表示在⼀个⽤户会话内有效。
requset,session 适⽤于 Web 项⽬。
singleton 模式下,只要加载 IoC 容器,⽆论是否从 IoC 中取出 bean,配置⽂件中的 bean 都会被创建。
prototype 模式下,如果不从 IoC 中取 bean,则不创建对象,取⼀次 bean,就会创建⼀个对象。
Spring 继承不同于 Java 中的继承,区别:Java 中的继承是针对于类的,Spring 的继承是针对于对象(bean)。
Spring 的继承中,子bean 可以继承父 bean 中的所有成员变量的值
通过设置 bean 标签的 parent 属性建⽴继承关系,同时⼦ bean 可以覆盖⽗ bean 的属性值。
Spring 的继承是针对对象的,所以⼦ bean 和 ⽗ bean 并不需要属于同⼀个数据类型,只要其成员变量列表⼀致即可。



