很多人卡在 Spring 入门这一关,不是 IoC 和 AOP 本身有多难,而是学习顺序反了——先抱着理论书背概念,再去搭项目,结果容器是什么都没见过,IoC 就成了天书。正确的路径是:先花半天把第一个 Spring 项目跑起来,再带着”对象到底是谁创建的”这个疑问回头看 IoC、依赖注入和 Bean 生命周期,最后补上 AOP,写出第一个 Web 应用。这篇文章按这个顺序走一遍,每一步都有可直接运行的代码,看完你手里就有一个能跑的项目。
为什么学 Spring 总被 IoC 和 AOP 绕晕?问题出在学习顺序
先说结论:IoC 和 AOP 不是两个孤立的名词,而是一套”先有容器、再切代码”的协作机制。初学者常见的三个坑:
- 从注解开始学:上来就背
@Component、@Autowired的用法,却不知道这些注解背后是谁在”干活”。注解只是开关,容器才是干活的人。 - 把 IoC 当成需要背诵的考点:IoC 的核心只有一句话——对象的创建和依赖关系的决定权,从你的代码手里交给了 Spring 容器。理解这一句比背十页笔记有用。
- AOP 学得太晚:很多人把 AOP 放到最后甚至跳过,结果写业务时满屏重复的日志和权限校验代码,体会不到切面编程的价值。
所以下面我们反过来,先动手。
搭建第一个 Spring 项目:从零到运行只要十几分钟
环境要求很简单:JDK 17 及以上(Spring Boot 3.x 的硬性要求)、Maven 或 Gradle、IDEA 或 VS Code。
新建一个 Maven 项目,pom.xml 里加上最核心的依赖:
<?xml version="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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>first-spring</artifactId>
<version>1.0.0</version>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
逐段解释:spring-boot-starter-parent 帮你统一了 Spring 全家桶的版本号,你不需要手动对齐 Spring Core、Spring Context 的版本,这是新手最容易翻车的地方;spring-boot-starter 是最小可用的依赖包,包含了 IoC 容器本身。
然后写启动类:
package com.example.firstspring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FirstSpringApp {
public static void main(String[] args) {
SpringApplication.run(FirstSpringApp.class, args);
}
}
逐段解释:@SpringBootApplication 这个注解做了三件事——声明这是一个配置类、开启自动配置(根据你引入的依赖自动装配组件)、开启组件扫描(默认扫描启动类所在包 com.example.firstspring 及其子包下的所有 @Component 等注解)。SpringApplication.run 这一行就是 IoC 容器的”开机键”,容器会在这一刻启动、创建并管理所有 Bean。
运行 main 方法,控制台没有报错、出现 Spring Boot 的启动 banner,你的第一个项目就跑起来了。
IoC 到底是什么:控制反转不是玄学
IoC(Inversion of Control,控制反转)是指对象实例化和依赖关系的控制权,从业务代码转移给 Spring 容器。容器负责”造对象、装依赖、管销毁”,你的代码只负责”声明需要什么”。
打个比方:没有 IoC 时,你要用订单服务,就得自己 new 一个订单服务、再 new 出它依赖的用户服务——对象之间的”组装关系”写死在业务代码里,一改需求就得满代码找 new。IoC 之后,你只需要在类上贴一个 @Component 说”我需要用户服务”,容器自动找到它、造好、塞给你。这就是”反转”:从”我主动找对象”变成”对象被动被送到我手上”。
容器的核心接口有两个,面试和实操都要知道区别:
| 接口 | 定位 | 特点 |
|---|---|---|
BeanFactory |
基础容器 | 懒加载,按需创建 Bean,功能原始 |
ApplicationContext |
高级容器 | 启动时就预加载所有单例 Bean,内置国际化、事件发布等功能,Spring Boot 默认用它 |
实际开发里你几乎不会直接接触这两个接口,Spring Boot 把它们藏在了启动过程里,但知道这个区别能帮你读懂很多报错信息。
依赖注入(DI)三种写法对比:构造器注入才是首选
依赖注入(Dependency Injection)是指容器在创建 Bean 时,主动把依赖对象”注入”到当前对象中,它正是 IoC 的实现手段。Spring 提供了三种写法:
| 注入方式 | 写法 | 优点 | 缺点 |
|---|---|---|---|
| 构造器注入 | 在构造函数参数上标注 | 支持不可变对象、便于单元测试、能检测循环依赖 | 参数多时构造函数较长 |
| Setter 注入 | 在 setter 方法上标注 | 可读性好,适合可选依赖 | 对象可变,依赖状态不清晰 |
| 字段注入 | 在字段上标 @Autowired |
一行搞定 | 无法声明为 final、难脱离容器测试 |
Spring 官方和大量实践都推荐构造器注入,尤其是只有一个构造函数时,@Autowired 都可以省略。来看完整示例:
package com.example.firstspring.repository;
public interface UserRepository {
String findUserName(Long id);
}
@Repository
public class UserRepositoryImpl implements UserRepository {
@Override
public String findUserName(Long id) {
return "用户" + id;
}
}
package com.example.firstspring.service;
import com.example.firstspring.repository.UserRepository;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String greet(Long id) {
return "你好," + userRepository.findUserName(id);
}
}
逐段解释:@Repository 和 @Service 是 @Component 的语义化特化,分别表示”数据访问层”和”业务层”,作用完全一样——告诉容器”这个类需要被管理”。UserRepositoryImpl 实现了接口,这是因为 Spring 默认用 JDK 动态代理实现 AOP 时要求目标类有接口。UserService 的构造器接收依赖,字段声明为 final,意味着对象一旦创建,依赖就是不可变的。容器启动时会自动发现:构造 UserService 需要 UserRepository,于是先造 UserRepositoryImpl,再把它装进 UserService——整个过程你一行组装代码都没写。
如果容器里有两个同类型 Bean,注入会失败,这时用 @Qualifier("具体bean名") 指定,或者用 @Primary 标记默认优先的那个。
Bean 生命周期:记住这条主线就够了
Bean 生命周期是指 Bean 从被容器实例化、到被销毁的完整过程。默认单例 Bean 的完整阶段如下:
| 阶段 | 触发方式 | 说明 |
|---|---|---|
| 1. 实例化 | 容器调用构造器 | 对象诞生,只完成了构造器代码 |
| 2. 属性赋值 | 依赖注入发生在这里 | @Autowired 的依赖被塞进来 |
| 3. Aware 回调 | 实现 BeanNameAware 等接口 |
Bean 拿到容器、类加载器等”环境信息” |
| 4. 前置后处理 | BeanPostProcessor |
常用于生成代理对象,AOP 在此生效 |
| 5. 初始化 | @PostConstruct → InitializingBean → 自定义 init-method |
业务初始化逻辑放这里 |
| 6. 使用中 | 容器把 Bean 交给调用方 | 单例 Bean 被共享复用 |
| 7. 销毁 | @PreDestroy → DisposableBean → 自定义 destroy-method |
容器关闭时释放资源 |
写个示例验证一下:
package com.example.firstspring;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component
public class OrderProcessor {
@PostConstruct
public void init() {
System.out.println("生命周期第5步:初始化完成,数据库连接已就绪");
}
public void processOrder(String orderId) {
System.out.println("生命周期第6步:处理订单 " + orderId);
}
@PreDestroy
public void cleanup() {
System.out.println("生命周期第7步:销毁,连接池正在关闭");
}
}
逐段解释:@PostConstruct 和 @PreDestroy 是 JSR-250 标准注解,在 Spring 里直接生效,分别对应初始化和销毁钩子。注意一个关键事实:生命周期回调方法里不能写业务逻辑以外的东西,更不能依赖其他还没初始化完的 Bean,否则容易踩到初始化顺序的坑。验证方式也很简单:启动时看控制台打印”初始化完成”,在 main 里调用 context.close() 或直接关闭程序时看”销毁”是否打印。
AOP 入门:切面到底切掉了什么
AOP(Aspect-Oriented Programming,切面编程)是指把散落在多个业务类中的重复逻辑(如日志、事务、权限校验)从主流程中剥离出来,以”切面”的形式集中维护。IoC 解决的是”对象谁来管”,AOP 解决的是”横切逻辑往哪放”。
Spring 实现 AOP 靠动态代理,代理方式的选择由容器自动决定:
| 方式 | 原理 | 触发条件 |
|---|---|---|
| JDK 动态代理 | 基于接口生成代理类 | 目标类实现了接口 |
| CGLIB | 基于继承生成子类代理 | 目标类没有接口 |
正因如此,上面的 UserRepository 才声明成接口——这正是 AOP 能生效的前提之一。来看切面代码:
package com.example.firstspring.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogAspect {
@Before("execution(* com.example.firstspring.service.*.*(..))")
public void beforeLog(JoinPoint joinPoint) {
System.out.println("[日志] 即将调用:" + joinPoint.getSignature().getName());
}
@AfterReturning(
pointcut = "execution(* com.example.firstspring.service.*.*(..))",
returning = "result"
)
public void afterLog(JoinPoint joinPoint, Object result) {
System.out.println("[日志] 调用结束,返回值:" + result);
}
}
逐段解释:@Aspect + @Component 声明这是一个切面组件;@Before 的第一个参数是切入点表达式,execution(* com.example.firstspring.service.*.*(..)) 表示”拦截 service 包下所有类的所有方法”;JoinPoint 是连接点对象,能拿到方法名、参数和返回值;@AfterReturning 的 returning = "result" 把返回值绑定到方法参数里。运行后你会发现:调用 UserService.greet 时,日志代码一行没写,日志却自动打印了——这就是 AOP 的价值。
写出第一个 Web 应用:REST 接口从 0 到 1
现在把前面学的全部串起来。pom.xml 追加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
然后依次写三层代码。仓储层:
package com.example.firstspring.repository;
import com.example.firstspring.model.Book;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class BookRepository {
private final List<Book> store = new ArrayList<>();
{ store.add(new Book(1L, "Spring实战", "Craig Walls")); }
public Book findById(Long id) {
return store.stream().filter(b -> b.getId().equals(id)).findFirst().orElse(null);
}
}
服务层(构造器注入登场):
package com.example.firstspring.service;
import com.example.firstspring.model.Book;
import com.example.firstspring.repository.BookRepository;
import org.springframework.stereotype.Service;
@Service
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public Book getBook(Long id) {
Book book = bookRepository.findById(id);
if (book == null) throw new IllegalArgumentException("图书不存在");
return book;
}
}
控制器层:
package com.example.firstspring.controller;
import com.example.firstspring.model.Book;
import com.example.firstspring.service.BookService;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
@GetMapping("/{id}")
public Book getBook(@PathVariable Long id) {
return bookService.getBook(id);
}
}
逐段解释:spring-boot-starter-web 一行依赖就带入了内嵌 Tomcat、Spring MVC 和 JSON 序列化,所以不再需要部署传统 WAR 包。@RestController = @Controller + @ResponseBody,返回值直接转成 JSON。@RequestMapping("/books") 给类加统一前缀,@GetMapping("/{id}") 对应 GET 请求,@PathVariable 把 URL 里的路径变量绑到方法参数。三层之间用构造器注入串联——这正是 IoC 落地的样子。
启动应用后,浏览器访问 http://localhost:8080/books/1,你能看到 JSON 返回的图书信息,整个请求链路里,你没有手动 new 过任何一个对象。
避坑清单:新手最常翻车的五件事
- JDK 版本不匹配:Spring Boot 3.x 必须 JDK 17+,用 JDK 8 会报一堆莫名其妙的编译错,先检查
java -version。 - Bean 扫不到:组件扫描默认只覆盖启动类所在包及其子包,把
@Service写在启动类旁边的兄弟包里就会注入失败,把启动类放在根包com.example下最稳妥。 - 字段注入图省事:现在省事,之后测试和重构都要还债,新建类直接写构造器。
- 单例 Bean 里存可变状态:默认 Bean 是单例、多线程共享的,把请求级状态写进字段会导致数据串号,Spring 官方明确建议 Bean 保持无状态。
- AOP 对同类内部调用不生效:切面拦截的是”外部调用进入代理对象”的入口,在类内部
this.method()直接调用不走代理,这是 AOP 最经典的坑。
常见问题
Q1:先学 IoC 理论还是先搭项目? 先搭项目。理论要在容器真实运行起来之后回看才有感觉,顺序反了容易陷入”背概念—忘概念—重背”的循环。
Q2:@Autowired 字段注入为什么不推荐? 字段注入无法把依赖声明为 final、对象状态可变,且单元测试时必须依赖 Spring 容器才能造出对象;构造器注入让依赖显式化,测试时直接 new 一个 mock 就能跑。
Q3:Bean 默认是单例的吗?并发安全吗? 默认 scope 是 singleton,一个容器只有一个实例,多线程共享。只要 Bean 不保存请求级可变状态(依赖只读、方法内局部变量),就是线程安全的。
Q4:AOP 和 Filter、拦截器有什么区别?
Filter 和拦截器作用于 HTTP 请求层面,面向”请求流程”;AOP 作用于方法层面,面向”代码逻辑”,能在服务层方法上织入逻辑,和 Web 层解耦,事务注解 @Transactional 就是靠 AOP 实现的。
Q5:学完这篇,下一步该学什么?
先把 MyBatis 或 JPA 接入项目跑通数据库,再学 @Transactional 事务管理,最后理解自动配置原理(读 spring.factories / AutoConfiguration.imports),这条线走完,Spring 入门就算真正通关了。