一、核心概念与底层原理
1. Spring 核心机制概述
Spring 框架有两大核心能力,分别是 IoC(控制反转) 与 AOP(面向切面编程),二者同时也是 Java 设计模式的典型工程落地:IoC 底层基于工厂模式实现,负责对象的创建、属性赋值与全生命周期管理;AOP 底层基于代理模式实现,用于实现横向功能的统一增强。其中 IoC 是整个 Spring 框架的核心基础,也是我们学习 Spring 的第一站。
2. IoC 控制反转的核心思想
IoC 全称 Inversion of Control,即控制反转 ,它的核心是将对象的创建与管理权进行反转。
在传统的 Java 开发中,我们需要使用某个对象时,必须手动通过 new 关键字完成实例化、属性赋值等全部操作,对象的生命周期完全由开发者自己控制。而在 Spring 框架中,这些工作全部交给 IoC 容器 完成,开发者不需要关心对象是如何创建的,只需要直接从容器中获取并使用即可。
我们可以用超市购物做一个简单的类比:传统开发方式就像自己拿着袋子去超市选购商品、装袋、再自己拎回家,全程都要自己动手;而 IoC 容器就像把袋子放在家门口,容器会自动帮我们装好需要的商品,我们直接打开袋子使用就可以了。
3. IoC 的底层实现原理
IoC 容器之所以能自动创建对象,核心依靠的是 Java 反射机制 ,完整的执行流程分为三步:
第一步,IoC 容器读取配置信息(可以是 XML 文件、注解、配置类),获取目标类的全限定类名;
第二步,通过反射加载类的字节码文件,调用类的无参构造方法完成对象的实例化;
第三步,通过反射调用类的 setter 方法,完成对象属性的赋值。
简单来说,IoC 就是我们预先通过配置告诉容器需要管理哪些对象,容器加载配置后,通过反射机制完成对象的创建与属性注入。
二、单 Bean 注册的三种实现方式
将对象放入 IoC 容器管理的过程称为 Bean 注册,Spring 提供了三种主流的实现方式,我们可以根据业务场景选择使用。
1. 基于 XML 配置文件实现
这是 Spring 早期最主流的实现方式,所有的对象配置都写在 XML 配置文件中,配置与代码完全分离。
实现的整体步骤为:首先在项目的 pom.xml 中引入 Spring 核心依赖;然后创建 XML 配置文件,通过 <bean> 标签声明需要容器管理的对象,用 <property> 标签完成属性赋值;最后通过 Spring 提供的 API 加载 XML 配置,初始化 IoC 容器并获取 Bean。
实体类 Student
java
package com.southwind.entity;
import lombok.Data;
@Data
public class Student {
private Integer id;
private String name;
private Integer age;
}
XML 配置文件 beans.xml(存放于 src/main/resources 目录下)
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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="student" class="com.southwind.entity.Student">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="22"></property>
</bean>
</beans>
测试类
java
package com.southwind;
import com.southwind.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) ioc.getBean("student");
System.out.println(student);
}
}
这种方式的优势是同一个类可以创建多个不同的 Bean 实例,配置与代码完全解耦;缺点是配置繁琐,需要编写大量标签,项目变大后维护成本很高。
2. 基于 @Component 注解实现
为了简化 XML 繁琐的配置,Spring 推出了注解驱动的开发方式,直接在类上添加注解即可完成 Bean 注册,也是目前日常开发最常用的方式。
实现步骤为:首先引入 Spring 核心依赖;然后在实体类上添加 @Component 注解,声明该类由 IoC 容器管理,基础属性通过 @Value 注解赋值;接着指定包扫描路径,让 IoC 容器自动扫描路径下所有带 @Component 的类并完成注册;最后加载注解配置初始化容器,获取对象。
Bean 在容器中的 id 默认是类名首字母小写,也可以通过 @Component("自定义id") 的方式手动指定。
带注解的 Student 实体类
java
package com.southwind.entity;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component(value = "abc")
public class Student {
@Value("1")
private Integer id;
@Value("李四")
private String name;
@Value("33")
private Integer age;
}
测试类
java
package com.southwind;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ioc = new AnnotationConfigApplicationContext("com.southwind.entity");
System.out.println(ioc.getBean("abc"));
}
}
注解方式的优势是配置极简,代码量少,开发效率很高;缺点是一个类默认只能创建一个 Bean 实例,灵活性相对较弱。
3. 基于 @Configuration 配置类实现
XML 配置繁琐,注解方式灵活性不足,因此 Spring 提供了第三种方式------配置类,它结合了前两者的优势:完全脱离 XML 文件,同时支持一个类创建多个 Bean 实例,也是 Spring 官方推荐的全 Java 开发模式。
配置类的核心思路是用一个 Java 类替代 XML 配置文件的功能,把原本写在 XML 中的 Bean 配置,转移到 Java 类的方法中实现。我们在配置类上添加 @Configuration 注解标记它为配置类,在方法上添加 @Bean 注解,方法的返回值就会被注册到 IoC 容器中,Bean 的 id 默认等于方法名。
Student 实体类(普通 POJO,无需添加注解)
java
package com.southwind.entity;
import lombok.Data;
@Data
public class Student {
private Integer id;
private String name;
private Integer age;
}
配置类 StudentConfiguration
java
package com.southwind.configuration;
import com.southwind.entity.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StudentConfiguration {
@Bean
public Student student(){
Student student = new Student();
student.setId(1);
student.setName("张三");
student.setAge(22);
return student;
}
}
测试类
java
package com.southwind;
import com.southwind.configuration.StudentConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ioc = new AnnotationConfigApplicationContext(StudentConfiguration.class);
System.out.println(ioc.getBean("student"));
}
}
配置类的优势是完全脱离 XML,配置灵活,支持一个类创建多个 Bean 实例,也支持复杂的对象组装逻辑;相对的缺点是配置与代码耦合度比 XML 更高。
三、对象级联(依赖注入 DI)
掌握了单个 Bean 的注册之后,我们进一步学习对象之间的依赖关系配置,也就是对象级联。它的本质就是 DI(Dependency Injection,依赖注入),是 IoC 思想的具体实现手段:当一个对象内部依赖另一个对象时,我们不需要手动创建并赋值依赖对象,IoC 容器会自动从容器中找到匹配的依赖对象,完成属性赋值,实现对象之间的关联绑定。
下面我们分别用三种配置方式实现 Student 类关联 Address 类的级联效果。
1. 基于 XML 的对象级联
XML 方式实现级联的思路很简单:先分别把 Student 和 Address 两个类配置为容器中的 Bean,再在 Student 的属性配置中,通过 ref 属性引用容器中 Address Bean 的 id,即可完成依赖注入。
实体类
java
package com.southwind.entity;
import lombok.Data;
@Data
public class Student {
private Integer id;
private String name;
private Integer age;
private Address address;
}
java
package com.southwind.entity;
import lombok.Data;
@Data
public class Address {
private Integer id;
private String value;
}
XML 配置文件 spring.xml
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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="address" class="com.southwind.entity.Address">
<property name="id" value="11"></property>
<property name="value" value="软件园"></property>
</bean>
<bean id="student" class="com.southwind.entity.Student">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="22"></property>
<property name="address" ref="address"></property>
</bean>
</beans>
测试类
java
package com.southwind;
import com.southwind.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(ioc.getBean("student"));
}
}
2. 基于注解的对象级联
注解方式实现级联依靠 @Autowired 注解,它可以实现自动装配:IoC 容器会默认按照类型,从容器中找到匹配的依赖对象,自动赋值给对应的属性。需要注意的是,被依赖的对象也必须注册到 IoC 容器中,否则会注入失败。
Address 实体类
java
package com.southwind.entity;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component
public class Address {
@Value("11")
private Integer id;
@Value("公司")
private String value;
}
Student 实体类
java
package com.southwind.entity;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component
public class Student {
@Value("1")
private Integer id;
@Value("李四")
private String name;
@Value("22")
private Integer age;
@Autowired
private Address address;
}
测试类
java
package com.southwind;
import com.southwind.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ioc = new AnnotationConfigApplicationContext("com.southwind");
System.out.println(ioc.getBean("student"));
}
}
3. 基于配置类的对象级联
配置类实现级联的方式最直接,我们在 @Bean 方法中手动创建依赖对象,完成属性赋值后,直接设置给主对象即可,完全由代码控制依赖关系。
实体类(普通 POJO,无注解)
java
package com.southwind.entity;
import lombok.Data;
@Data
public class Student {
private Integer id;
private String name;
private Integer age;
private Address address;
}
java
package com.southwind.entity;
import lombok.Data;
@Data
public class Address {
private Integer id;
private String value;
}
配置类 StudentConfiguration
java
package com.southwind.configuration;
import com.southwind.entity.Address;
import com.southwind.entity.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StudentConfiguration {
@Bean
public Student student(){
Student student = new Student();
student.setId(1);
student.setName("张三");
student.setAge(22);
Address address = new Address();
address.setId(22);
address.setValue("科技园");
student.setAddress(address);
return student;
}
}
测试类
java
package com.southwind;
import com.southwind.configuration.StudentConfiguration;
import com.southwind.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ioc = new AnnotationConfigApplicationContext(StudentConfiguration.class);
System.out.println(ioc.getBean("student"));
}
}
四、总结与注意事项
1. 三种实现方式对比
| 实现方式 | 配置形式 | 多实例支持 | 开发效率 | 解耦程度 |
|---|---|---|---|---|
| 基于 XML | XML文件 | 支持 | 低 | 高 |
| 基于 @Component | 类上注解 | 默认不支持 | 高 | 中 |
| 基于配置类 | Java类 | 支持 | 中 | 中 |
2. 混合使用的兼容规则
实际开发中我们经常会混合使用多种配置方式,需要注意它们的兼容与冲突规则:
- 配置类和 @Component 注解方式:如果同一个 Bean 的 id 重复,注解创建的 Bean 会覆盖配置类中的 Bean,同类型的 Bean 不建议两种方式混用。
- 配置类和 XML 方式:二者完全不冲突,可以混合使用。
- 注解和 XML 方式:二者完全不冲突,可以同时存在,分别管理不同的 Bean。
3. 核心概念辨析
最后我们区分两个非常容易混淆的概念:
- Bean 注册 :动作是"把对象放进 IoC 容器",对应的语法是
<bean>标签、@Component、@Bean。 - 依赖注入(对象级联) :动作是"从容器中取出对象,赋值给类的属性",对应的语法是
ref属性、@Autowired、手动 setter 赋值。
简单来说,注册是存,注入是取,二者共同组成了 IoC 容器的核心能力。