目录
1.IOC介绍
IOC(Inversion of Control) 控制反转,解决类之间关联性太高导致的高耦合度的问题。
如果类之间的耦合度过高,会导致在对功能更新时要进行大面积重复性工作,这种情况肯定不是我们想要的,尤其是当项目很庞大时,这种重复性工作不仅没有意义而且很耗费时间,因此IOC容器来了,它能有效的解决这个问题,降低类之间的关联性。 Spring框架提供的IoC容器进行对象的管理,一个由Spring IoC容器实例化、组装和管理的对象,我们称其为Bean。 使用目的:降低耦合度。
2.IOC容器XML配置文件使用方式:
1.IOC的使用
在maven中导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.10</version>
</dependency>
resource下创建Spring配置文件application.xml并且写入代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
Spring默认提供了一个IOC容器,用于存放和管理使用的对象。我们是用配置文件,因此我们要使用ClassPathXmlApplicationContext,传入刚刚创建的xml文件。
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
}
}
然后我们再创建一个Student类来测试
public class Student {
public void method(){
System.out.println("student");
}
}
在XML文件中加入该类的bean,这样我们就可以从IOC容器中通过name或者类来获取Student类的对象
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="Student" class="org.example.entity.Student"/>
</beans>
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
//Student student1 = context.getBean(Student.class);
Student student = (Student) context.getBean("Student");
student.method();
}
}
2.bean的使用
不同的Spring配置文件可以互相进行导入,使用import即可,比如我们又创建了一个test.xml文件
<beans ......>
<import resource="test.xml"/>
</beans>
在bean的使用中还会出现一些问题,比如当我们在getBean()时不能明确的指明获取哪个类,就会出现异常,比如我们同时有两个类Test1,Test2继承了同一个父类Student,如果此时getBean(Student.class)就会出现异常,因此Spring不知道指的是哪一个,因此我们在getBean时不要出现歧义。 在对bean进行配置时,还可以对bean起别名,比如我们已经给Student类配置name属性了,我们还可以通过alias来再给他起别名。依然可以通过getBean(name)来获得
<bean name="Student" class="com.test.bean.Student"/>
<alias name="Student" alias="student"/>
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Student student = (Student) context.getBean("student");
student.method();
}
}
在默认情况下bean只会将对象创建一次,作用域为Singleton类似单例模式,也就是说我们每一次getBean同一个类时获取的对象都是同一个,因此获取两次对象并且判断是否相等时返回的会是true
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Student student = (Student) context.getBean("student");
Student student1 = (Student) context.getBean("Student");
System.out.println(student1 == student);
}
}
但是我们可以修改scope属性来让每一次getBean时创建新的对象,prototype代表的是原型模式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="Student" class="org.example.entity.Student" scope="prototype"/>
</beans>
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Student student = context.getBean(Student.class);
Student student1 = context.getBean(Student.class);
System.out.println(student1 == student);
}
}
将scope改为singleton,单例模式下,每一个对象都是在获取IOC容器时就已经加载好了,我们给构造方法加一行输出
public class Student {
public Student(){
System.out.println("Student已创建");
}
public void method(){
System.out.println("hello");
}
}
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
}
}
在单例模式下,我们还可以控制是否在获取容器时就创建对象,开启懒加载后就可以让对象在第一次getBean时才创建对应的对象
<bean class="com.test.bean.Student" lazy-init="true"/>
此时不会直接在获取容器时创建对象
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
}
}
将scope改为prototype,对象只会在每一次getBean时创建
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Student student = context.getBean(Student.class);
Student student1 = context.getBean(Student.class);
//只会输出两次,因此在获取IOC容器时并没有创建对象,而在getBean时会创建对象,并且是不同的
}
}
并且我们还可以控制不同Bean加载的顺序,通过depends_on属性就可以设置前置的加载Bean
public class Teacher {
public Teacher(){
System.out.println("Teacher已创建");
}
}
<bean name="teacher" class="com.test.bean.Teacher"/>
<bean name="student" class="com.test.bean.Student" depends-on="teacher"/>
这样Teacher的Bean就一定会在Student的Bean前面加载
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Student student = context.getBean(Student.class);
}
}
3.依赖注入
依赖注入时解决类关联性过高的重要设计模式,比
public class Student {
Teacher teacher;
public Student(){
System.out.println("Student已创建");
}
public void method(){
System.out.println("hello");
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
现在我们的学生需要数学老师,那我们就需要给学生加入一个Teacher属性并且new 数学老师对象,但设想一下,如果我们现在需要换老师,将数学老师换为音乐老师,并且有两万个学生,每个学生都要更改new 的对象,这个工作量时巨大的,但现在有了依赖注入我们无需提前new,而是在bean中配置好,更改它即可。 我们先写两个类来继承老师类,并且给Student添加属性
public class MathTeacher extends Teacher{
public MathTeacher(){
System.out.println("我是数学老师");
}
}
public class MusicTeacher extends Teacher{
public MusicTeacher(){
System.out.println("我是音乐老师");
}
}
set方法初始化:然后我们在配置文件中加入MathTeacher和MusicTeacher,并且使用property给Student的teacher属性指定是哪个老师,此时Student中必须有setTeacher方法才可以
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-lazy-init="true">
<bean name="MathTeacher" class="org.example.entity.MathTeacher"/>
<bean name="MusicTeacher" class="org.example.entity.MusicTeacher"/>
<bean name="Student" class="org.example.entity.Student">
<property name="teacher" ref="MathTeacher"/>
</bean>
</beans>
此时如果我们需要将数学老师换成音乐老师,只需要更改一下ref就能做到,怎么样,是不是很便捷,就算有两万名学生,也只需要将ref更改一下就可以
<property name="teacher" ref="MusicTeacher"/>
bean还可以用来指定属性的值,比如现在我们Student中有name属性,我们就可以通过property来指定name属性的值
<property name="name" value="张三"/>
构造方法初始化:我们也可以不通过set方法而是构造方法来初始化成员属性,这需要constructor-arg
比如我们现在将Student类改为
public class Student {
Teacher teacher;
public Student(){
System.out.println("Student已创建");
}
public Student(Teacher teacher){
this.teacher = teacher;
System.out.println("Student已创建,并且teacher已初始化");
}
public void method(){
System.out.println("hello");
}
}
并且加入constructor-arg,这个属性的数量就是构造方法参数的数量,会自动匹配符合参数数量的构造方法,如果找不到就会报错
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="MathTeacher" class="org.example.entity.MathTeacher"/>
<bean name="MusicTeacher" class="org.example.entity.MusicTeacher"/>
<bean name="Student" class="org.example.entity.Student">
<constructor-arg name="teacher" ref="MathTeacher"/>
</bean>
</beans>
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Student student = context.getBean(Student.class);
}
}
如果出现了警告
12月 17, 2022 3:26:26 下午 org.springframework.core.LocalVariableTableParameterNameDiscoverer inspectClass
警告: Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: XXXX
这是因为LocalVariableTableParameterNameDiscoverer在Spring 6.0.1版本已经被标记为过时,并且即将移除,请在Maven配置文件中为编译插件添加-parameters
编译参数:clean后再运行就好了
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
那么问题来了,如果出现了有两个参数数量相同的构造方法怎么办呢?没关系,我们还可以指定参数的类型
<constructor-arg name="teacher" ref="MathTeacher" type="org.example.entity.Teacher"/>
当我们的成员属性类型比较特殊,为集合时,我们还可以指定集合里的值,这里以map演示,如果我们有一个属性时map,我们通过以下方式来依赖注入
<bean name="student" class="com.test.bean.Student">
<property name="map">
<map>
<entry key="语文" value="95.0"/>
<entry key="数学" value="82.0"/>
<entry key="英语" value="90.0"/>
</map>
</property>
</bean>
4.自动装配
自动装配是让IOC容器自己寻找需要填入的值
set方法自动装配:
<bean name="Student" class="org.example.entity.Student" autowire="byType"/>
public class Student {
MathTeacher teacher;
public Student(){
System.out.println("Student已创建");
}
public void method(){
System.out.println("hello");
}
public void setTeacher(MathTeacher teacher) {
this.teacher = teacher;
}
}
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Student student = context.getBean(Student.class);
}
}
但是如果我们的Student属性的MathTeacher改为Teacher根据类型寻找,set方法参数也改为Teacher teacher,就会由于有多个Teacher类的子类而导致出错,如果我们想在任何情况下都不让一个类参与自动装配,那我们就可以给该类的Bean添加autowire-candidate="false"属性 ,这样就不会出错 或者 我们也可以设置优先级primary=true,当出现歧义时,优先级更高的会优先装配。
5.Bean的生命周期
如果当前为单例模式,bean在获取容器时便加载好,并且我们可以设置初始化方法来观察到,也可以设置销毁时的方法,在容器关闭时会自动调用
<bean name="Student" class="org.example.entity.Student" init-method="init" destroy-method="destroy"/>
public class Student {
public Student(){
System.out.println("Student已创建");
}
public void init(){
System.out.println("StudentBean已加载");
}
public void destroy(){
System.out.println("StudentBean已被销毁");
}
public void method(){
System.out.println("hello");
}
}
public class Main {
public static void main(String[] args) {
//IOC容器创建
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
context.close();
}
}
而在原型模式下,调用close方法不会执行destroy方法,但初始化方法依旧会执行
6.Bean的继承
Bean之间也是可以继承属性的,通过parent方法可以获取指定bean的属性,当然,如果一个Bean的abstract属性设置为true,那他就无法被其他的Bean继承,这样看,Bean和类的相似点还是很多的。
7.工厂Bean
有时我们希望 Spring不要直接利用反射机制通过构造方法创建对象,此时我们就要使用工厂Bean来实现这个效果
<bean class="org.example.factory.StudentFactory" factory-method="getStudent"/>
学生类和学生工厂类
public class Student {
public Student(){
System.out.println("Student已创建");
}
public void method(){
System.out.println("hello");
}
}
public class StudentFactory {
public static Student getStudent(){
System.out.println("制作一个学生");
return new Student();
}
}
factory-method方法得到的是一个Student,因此在getBean时获取Student类即可
public class Main {
public static void main(String[] args) {
//IOC容器创建
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
context.getBean(Student.class).method();
}
}
我们也可以直接注册一个工厂bean,这样必须先拿到工厂的对象才能创建对象
<bean name="studentFactory" class="org.example.factory.StudentFactory"/>
<bean factory-bean="studentFactory" factory-method="getStudent"/>
public class StudentFactory {
public Student getStudent(){
System.out.println("制作一个学生");
return new Student();
}
}
public class Main {
public static void main(String[] args) {
//IOC容器创建
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
context.getBean(StudentFactory.class).getStudent();
}
}
还有一些其他的属性,大家可以自行学习
3.注解开发
我们已经学会如何使用XML文件,但是XML文件有一定缺点,比如后期可能XML文件过大并且XML文件配置不方便也不好查找,因此注解开发应运而生
XML文件要使用ClassPathXmlApplicationContext方法获取到IOC容器,现在我们使用注解,要使用AnnotationConfigApplicationContext()获取IOC容器,并且使用配置类还代替XML文件
@Configuration
public class MainConfiguration {
}
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfiguration.class);
}
}
Student的Bean这样创建,获取对象的方式依旧是getBean,其他的一些属性可以在@Bean以及其他注解里面设置,默认name为类的小驼峰命名
@Configuration
public class MainConfiguration {
//@Bean(name = "", initMethod = "", destroyMethod = "", autowireCandidate = false)
//@Lazy(true) //对应lazy-init属性
//@Scope("prototype") //对应scope属性
//@DependsOn("teacher") //对应depends-on属性
@Bean
public Student student(){
return new Student();
}
}
当我们Student中有参数Teacher teacher时,可以直接通过构造法将Student的Bean的name作为参数传入会自动初始化
public class Teacher {
public Teacher(){
System.out.println("Teacher已创建");
}
}
public class Student {
Teacher teacher;
public Student(){
System.out.println("Student已创建");
}
public Student(Teacher teacher){
System.out.println("Student已创建,并且teacher已初始化");
}
public void method(){
System.out.println("hello");
}
}
@Configuration
public class MainConfiguration {
@Bean
public Teacher teacher(){
return new Teacher();
}
//@Bean(name = "", initMethod = "", destroyMethod = "", autowireCandidate = false)
//@Lazy(true) //对应lazy-init属性
//@Scope("prototype") //对应scope属性
//@DependsOn("teacher") //对应depends-on属性
@Bean
public Student student(Teacher teacher){
return new Student(teacher);
}
}
当然,配置类依旧也可以使用自动装配,@Autowired注解默认使用ByType
public class Student {
@Autowired
Teacher teacher;
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public Student(){
System.out.println("Student已创建");
}
}
public class Teacher {
public Teacher(){
System.out.println("Teacher已创建");
}
}
@Configuration
@Lazy(true)
public class MainConfiguration {
@Bean
public Teacher teacher(){
return new Teacher();
}
//@Bean(name = "", initMethod = "", destroyMethod = "", autowireCandidate = false)
//@Lazy(true) //对应lazy-init属性
//@Scope("prototype") //对应scope属性
//@DependsOn("teacher") //对应depends-on属性
@Bean
public Student student(){
return new Student();
}
}
public class Main {
public static void main(String[] args) {
//IOC容器创建
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfiguration.class);
}
}
如果我们有多个相同类型的Bean,我们可以通过@Autowired和@Qualifier来匹配
@Configuration
@Lazy()
public class MainConfiguration {
@Bean
public Teacher TeacherA(){
return new Teacher();
}
@Bean
public Teacher TeacherB(){
return new Teacher();
}
//@Bean(name = "", initMethod = "", destroyMethod = "", autowireCandidate = false)
//@Lazy(true) //对应lazy-init属性
//@Scope("prototype") //对应scope属性
//@DependsOn("teacher") //对应depends-on属性
@Bean
public Student student(){
return new Student();
}
}
public class Student {
@Autowired
@Qualifier("TeacherA")
Teacher teacher;
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public Student(){
System.out.println("Student已创建");
}
}
学习参考:
如有错误,感谢纠正。