Spring 学起来一头雾水,多半是因为 IoC、AOP、自动装配这几个词一上来就糊你一脸。其实一句话就能说清:IoC 是让 Spring 容器替你创建和管理对象,AOP 是让 Spring 帮你把散落在各处的公共逻辑(日志、事务、权限校验)统一收拢,自动装配则是 Spring 按规则替你完成依赖注入。本文不讲空理论,直接从零搭一个能跑的 SpringBoot 项目,把三个概念一一对应到项目里每一行代码上,看完你再回头看这些概念就全通了。
先看没有 Spring 的日子有多痛苦
在写 Spring 之前,先花两分钟看看没有它的时候代码长什么样:
public class UserService {
// 自己 new 依赖,Service 和 Mapper 死死绑在一起
private UserMapper userMapper = new UserMapper();
public User getUser(Long id) {
return userMapper.findById(id);
}
}
这种写法有三个麻烦:依赖是硬编码的(想换成测试用的假 Mapper,得改源码);换实现要改一堆地方(每处调用都要 new 一遍);单元测试很难写(没法用假对象替换真实数据库操作)。Spring 要解决的就是这件事——把”谁创建对象、谁管理依赖”这件事接管过去。
IoC 是什么?控制反转到底”反转”了什么
IoC(Inversion of Control,控制反转)是指对象创建和依赖关系的管理权从程序员手里转移到 Spring 容器手里的一种设计模式。它是一种思想,而依赖注入(Dependency Injection,DI)是实现它的主要方式:对象不再自己 new 依赖,而是由容器在运行时把依赖”送”进来。
容器里托管的对象叫 Bean,它的一生大致是这样的:
- 实例化:容器调用构造器创建对象;
- 属性填充:注入依赖(自动装配就在这一步发生);
- Aware 回调、BeanPostProcessor 前后处理;
- 初始化:执行
@PostConstruct或InitializingBean的方法; - 使用;
- 销毁:容器关闭时执行
@PreDestroy。
所以”控制反转”反的正是”自己 new”这个控制权——你原来控制”谁来创建对象”,现在把这个权力交给容器,你只管声明”我需要什么”。
AOP 是什么?为什么日志和事务要交给它
AOP(Aspect-Oriented Programming,面向切面编程)是一种把横切关注点(cross-cutting concerns)从业务逻辑中分离出来的编程范式。什么叫横切关注点?就是”每个方法都要做、但和业务没关系”的事:打日志、记耗时、权限校验、事务管理。
如果没有 AOP,你得在每个方法里重复写:
public User getUser(Long id) {
long start = System.currentTimeMillis(); // 每个方法都抄一遍
User user = userRepository.findById(id);
log.info("耗时: " + (System.currentTimeMillis() - start) + "ms");
return user;
}
AOP 让你把这些代码抽到一个”切面”里,用规则声明”哪些方法需要套上这段逻辑”,Spring 在运行时帮你织进去。它靠动态代理实现:对代理对象调用方法时,先执行切面逻辑,再进入真实方法。Spring 有两种代理方式:
| 代理方式 | 实现原理 | 适用条件 |
|---|---|---|
| JDK 动态代理 | 基于接口生成代理类 | 目标类实现了接口 |
| CGLIB | 运行时生成目标类的子类 | 目标类没有接口也能用 |
Spring Boot 2.x 起默认统一用 CGLIB 代理(spring.aop.proxy-target-class=true),所以不实现接口也能被 AOP 增强——这也是为什么你写的 @Service 类没实现任何接口,@Transactional 依然生效。
自动装配(Autowiring)是怎么回事
自动装配通俗地说就是:Spring 扫描容器里的 Bean,按规则自动把依赖塞进你的属性或构造器。开启它靠的是 @Autowired,配合 @ComponentScan(或 @SpringBootApplication 自带的组件扫描)让容器”发现”所有标了 @Service、@Repository、@Component 的类。
按什么规则装配?默认两个维度:
- 按类型注入(byType):容器里同类型的 Bean 只有一个时,直接注入。这是默认行为,写
@Autowired就是按类型来; - 按名称注入(byName):字段名和 Bean 名一致时注入,配合
@Autowired+@Qualifier("userMapper")指定名字。
有个实践建议要强调:优先用构造器注入,少用字段注入。字段注入(@Autowired 直接怼在字段上)写起来快,但对象没构造完就注入依赖,无法声明不可变字段,单测时必须 Spring 容器才能跑起来;构造器注入天然保证了依赖不可变,且不依赖容器也能 new 出来测试。
// 推荐:显式构造器,依赖不可变,单测友好
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
从零搭一个 SpringBoot 项目
环境很简单:JDK 17 以上(用 Spring Boot 3.x 必须 17+)、IDEA 或任意编辑器、Maven。下面四步走,每一步都对应前文某个概念。
第一步:创建项目并引入依赖
新建 Maven 项目,pom.xml 这样写:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- 父 POM 统一管理 Spring 全家桶版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-demo</artifactId>
<version>0.0.1-Spring</version>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<!-- Web:内嵌 Tomcat + SpringMVC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- AOP:切面编程必备 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
注意 spring-boot-starter-aop 是独立依赖,不引它 @Aspect 不生效——这是新手最常见的”切面没反应”原因。
第二步:写启动类
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@SpringBootApplication 是个组合注解,等于 @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan:扫描当前包及子包下的所有组件,并根据 classpath 自动装配 Tomcat、数据源等配置——这就是”自动装配”在 Boot 层面的含义:jar 包里有什么,Spring 就自动配什么。
第三步:分层写业务代码
先写数据访问的假仓库(内存 List 代替数据库):
package com.example.repository;
import com.example.entity.User;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository // 标记为 Bean,容器会实例化并管理它
public class UserRepository {
private final List<User> db = new ArrayList<>();
public UserRepository() {
db.add(new User(1L, "小明"));
db.add(new User(2L, "小红"));
}
public User findById(Long id) {
return db.stream()
.filter(u -> u.getId().equals(id))
.findFirst()
.orElse(null);
}
}
再写 Service——注意这里没有 new UserRepository,依赖由容器送来:
package com.example.service;
import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
// 构造器注入:容器发现 UserRepository 这个 Bean,装配进来
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getUser(Long id) {
return userRepository.findById(id);
}
}
最后是 Controller:
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public User get(@PathVariable Long id) {
return userService.getUser(id);
}
}
User 实体类就是普通的 id + name 加 getter/setter,这里从简。
第四步:加一个切面,验证 AOP
package com.example.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect // 声明这是一个切面
@Component
public class LogAspect {
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
// 拦截 service 包下所有方法的执行
@Around("execution(* com.example.service..*.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object result = pjp.proceed(); // 进入真实方法
log.info("{} 执行耗时 {}ms", pjp.getSignature(), System.currentTimeMillis() - start);
return result;
}
}
@Around 是环绕通知,pjp.proceed() 之后才进入 UserService.getUser 的真实逻辑。切面里没写任何业务代码,却给所有 Service 方法加上了耗时统计——这就是 AOP 的价值。
跑起来看效果
在项目根目录执行 mvn spring-boot:run,或直接在 IDEA 里运行 DemoApplication 的 main 方法。启动成功后访问:
curl http://localhost:8080/user/1
浏览器返回:
{"id":1,"name":"小明"}
同时控制台会打出类似这样的日志:
UserService.getUser 执行耗时 2ms
这条日志不是业务代码写的,是切面织进去的。到这里,整条链路你应该能看明白了:启动类扫描到三个 Bean(IoC 容器接管对象生命周期)→ 构造器注入完成依赖装配(自动装配)→ 请求进来,走代理对象,切面先执行再进真实方法(AOP)。
三个概念在项目里的对照
| 概念 | 对应到本项目哪里 |
|---|---|
| IoC | @Repository/@Service/@Component 标记的类由容器创建管理,程序员不 new |
| 依赖注入 | UserService 构造器里的 UserRepository 由容器传入 |
| 自动装配 | @SpringBootApplication 按 classpath 自动配内嵌 Tomcat、@Autowired 按类型注入 |
| AOP | LogAspect 拦截 service 包方法,自动记录耗时 |
| 动态代理 | UserService 被 CGLIB 生成了子类代理,请求先进代理再进真实对象 |
新手最容易踩的几个坑
- 字段注入别滥用。
@Autowired怼在字段上快,但依赖不可变性和可测性都差,团队项目建议强制构造器注入。 - 循环依赖报错。两个 Bean 构造器互相注入会启动失败,因为构造时谁都还没造出来。能用 setter 注入解决一部分,但更推荐重新设计拆分职责。
- AOP 自调用失效。同一个类里
this.getUser()绕过了代理对象,切面不生效——这是 AOP 最经典的坑,解决办法是把方法拆到另一个 Bean 里,或用AopContext.currentProxy()。 - 非 Spring 管理的类里 @Autowired 是 null。自己
new出来的对象不在容器里,注解根本不生效。 - Boot 2 和 3 的包名差异。Boot 3 的包名从
javax.*换成了jakarta.*,抄老教程报错时先检查这个。
常见问题
IoC 和 DI 有什么区别?
IoC 是”控制权交给容器”这个设计思想,DI(依赖注入)是实现它的具体手段。你可以理解为:IoC 是目标,DI 是 Spring 达成目标的方式,日常讨论中两者经常混着叫。
@Autowired 按类型注入时出现多个同类型 Bean 怎么办?
会报 NoUniqueBeanDefinitionException。解决办法二选一:用 @Qualifier("beanName") 指定名字,或者改用按名称注入(字段名与 Bean 名一致)。
Spring 和 SpringBoot 是什么关系?
Spring 是 IoC/AOP 容器的本体,SpringBoot 是套在它外面的脚手架,通过 starter 依赖和自动配置帮你把项目快速跑起来。SpringBoot 底层依然是 Spring,学懂了 IoC 和 AOP,Boot 只是省去了 XML 配置。
AOP 一定要实现接口才能用吗?
不必须。Spring Boot 2.x 起默认用 CGLIB 代理,通过生成子类的方式织入逻辑,不实现接口的类同样能被增强。
学 Spring 前需要先学 SSM 或 SSH 吗?
不需要。老教程里的 XML 配置(struts、hibernate XML)今天基本淘汰了,直接从 SpringBoot 入手反而是当前主流路线,把时间花在理解 IoC、AOP、Bean 生命周期这些不变的核心上更划算。
到这里你应该能感觉到:Spring 并没有那么玄,IoC 管对象、AOP 管横切、自动装配管依赖,三个概念各管一摊,串起来就是整个框架的骨架。建议你亲手把这个项目敲一遍、改一改——比如给切面换个切入点表达式,或者故意制造一次循环依赖看看报错——比看十篇文章都管用。