如果你刚接触 Spring 框架,被 IoC、AOP、Bean 这些英文缩写绕得晕头转向,先别慌——这份学习路线会把每个概念都落到能跑通的代码和真实开发场景里。先给结论:Spring 框架本质上是一个“对象工厂 + 管理器”:IoC 是把对象的创建权交给容器的设计思想,Bean 是容器里被管理的对象,AOP 是把散落在各个业务方法里的横切逻辑(如日志、事务)统一抽出来处理的编程方式。 按下面的路线走,零基础大约 4 到 6 周就能独立写出一个带依赖注入和日志切面的 Spring 项目。
Spring框架到底是什么?先把IoC、AOP、Bean三个词拆开
很多初学者被绕晕,是因为教程习惯把三个概念混在一起讲。拆开看其实不难:
- IoC(控制反转,Inversion of Control)是指:对象不再由程序员自己用
new创建,而是交给 Spring 容器统一创建和管理,程序的“控制权”从业务代码反转到了容器手里。 - Bean 是指:凡是交给 Spring 容器创建和管理的 Java 对象,都叫 Bean。你可以把它理解为“容器户口簿上的登记对象”。
- AOP(面向切面编程,Aspect-Oriented Programming)是指:把日志、事务、权限校验这类“横切多个业务方法、但又不是任何一个业务本身”的逻辑,单独抽成一个“切面”,由容器在方法调用前后自动织入。
打个比方:IoC 就像公司不自己招人,而是统一走人力资源部门(容器);Bean 是登记在册的员工;AOP 则是“上下班打卡”这件事——每个员工都要做,但没必要每个岗位单独写一遍,打卡系统统一处理即可。
这里提醒一个坑:网上很多老教程用的是 XML 配置(applicationContext.xml),而 2013 年之后的官方教程和所有新项目都用注解 + Java 配置。建议零基础直接学注解方式,XML 只需了解即可。
搭建第一个Spring项目:从pom.xml到跑通第一行输出
环境要求先说清楚:Spring 6.x 需要 JDK 17 及以上(Spring Boot 3.x 同理),如果你还在用 JDK 8,请先升级,否则依赖会装不上。
第一步,Maven 项目里引入核心依赖(只需这一个就能跑通第一个程序):
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.6</version>
</dependency>
</dependencies>
第二步,写一个普通的 Java 类:
public class User {
private String name;
private int age;
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
@Override
public String toString() {
return "User{name='" + name + "', age=" + age + "}";
}
}
第三步,声明一个配置类,告诉容器“有一个 User 对象归你管”:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public User user() {
return new User("张三", 25);
}
}
第四步,启动:
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
User user = context.getBean(User.class);
System.out.println(user);
}
}
运行后输出 User{name='张三', age=25}。逐段解释一下:@Configuration 标记这是一个配置类,@Bean 告诉容器“这个方法的返回值是一个 Bean”,AnnotationConfigApplicationContext 就是 IoC 容器的入口——容器启动时读取配置类,实例化 Bean,之后你通过 getBean 拿到的是容器统一管理的那个对象,而不是你自己 new 的。
IoC和DI在反转什么?对比“没有Spring”的写法就懂了
IoC 常和 DI(依赖注入, Dependency Injection) 一起出现。DI 是指 IoC 的一种具体实现方式:容器不仅创建对象,还把对象所依赖的其他对象“注入”进来。
看没有 Spring 时的经典写法:
public class OrderService {
// 自己 new,OrderService 和 PaymentService 就焊死了
private final PaymentService paymentService = new PaymentService();
}
问题很实际:PaymentService 换成微信支付实现,OrderService 就得改代码重编译;想给 OrderService 写单元测试,也没法替换掉这个依赖。
改用 Spring 之后:
@Component
public class PaymentService {
public void pay(double amount) {
System.out.println("支付了 " + amount + " 元");
}
}
@Service
public class OrderService {
private final PaymentService paymentService;
// 构造器注入:容器负责把 PaymentService 传进来
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
public void placeOrder(double amount) {
System.out.println("下单");
paymentService.pay(amount);
}
}
配置类开启组件扫描:
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {}
启动类:
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
context.getBean(OrderService.class).placeOrder(99.9);
}
}
@Component 和 @Service 都是“把这个类登记成 Bean”的注解(@Service 语义上专指业务层,@Controller 专指控制器),@ComponentScan 让容器自动扫描指定包下的所有 Bean 并完成注入。此时 OrderService 完全不知道 PaymentService 是谁创建的——控制权反转了,这就是 IoC 的全部含义。生产项目中更常用 @Autowired 完成注入,但构造器注入在官方文档中被推荐,因为它让依赖不可变、便于测试。
Bean的生命周期是怎么走的?五个阶段记牢
Bean 不是创建完就完事了,容器对它有完整的一生。Bean 的生命周期是指容器从实例化到销毁一个 Bean 所经历的全部过程,共五个阶段:实例化 → 属性赋值 → 初始化 → 使用 → 销毁。
用代码验证一遍:
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component
public class ReportTask {
public ReportTask() {
System.out.println("1. 实例化:构造器执行");
}
@PostConstruct
public void init() {
System.out.println("2. 初始化:@PostConstruct 回调执行");
}
public void run() {
System.out.println("3. 使用:执行业务方法");
}
@PreDestroy
public void destroy() {
System.out.println("4. 销毁:@PreDestroy 回调执行");
}
}
启动类(注意用 GenericApplicationContext,因为要手动触发销毁):
import org.springframework.context.GenericApplicationContext;
public class Main {
public static void main(String[] args) {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(ReportTask.class);
context.refresh();
context.getBean(ReportTask.class).run();
context.close();
}
}
输出顺序就是 1→2→3→4。几个实用结论:@PostConstruct 适合做资源初始化(如连接池预热),@PreDestroy 适合做资源释放;XML 时代的 init-method / destroy-method 属性现在用得少了;面试常追问的“单例 Bean 是线程安全的吗”也出在这个阶段——默认单例意味着所有请求共享同一个 Bean,有状态字段要自己小心。
AOP适合放哪些逻辑?用日志切面做示范
判断标准很简单:这段逻辑是否“横跨”多个业务方法,但又不属于任何一个业务本身? 日志记录、方法耗时统计、事务管理、权限校验都符合;下单扣库存这种业务逻辑绝对不能放。
AOP 依赖比核心包多两个:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>6.1.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.22.1</version>
</dependency>
写切面:
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 {
// 拦截 com.example.service 包下所有类 的所有方法
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("[日志] 即将调用:" + joinPoint.getSignature().getName());
}
@AfterReturning(
pointcut = "execution(* com.example.service.*.*(..))",
returning = "result")
public void logAfter(JoinPoint joinPoint, Object result) {
System.out.println("[日志] " + joinPoint.getSignature().getName()
+ " 正常返回,结果:" + result);
}
}
配置类开启代理:
@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
public class AppConfig {}
再调用一次上一节的 placeOrder,你会看到切面日志自动打印在业务代码前后,业务方法一行没改。原理一句话:Spring 在运行时为这些方法生成代理对象,你的调用先经过代理,代理再织入切面逻辑——这就是 AOP 的“织入”。@Before、@AfterReturning 是通知类型,execution(...) 是切点表达式,这两个记住,AOP 就入门了。
零基础学Spring的完整路线怎么排?
概念跑通之后,按下面的节奏推进,每阶段都有明确的验收标准:
| 阶段 | 学什么 | 建议时长 | 验收标准 |
|---|---|---|---|
| 一 | IoC/DI、Bean 生命周期、AOP | 2 周 | 脱离教程,独立写出上面的第一个项目 |
| 二 | Spring MVC、拦截器、统一异常处理 | 2 周 | 手写一个返回 JSON 的接口 |
| 三 | Spring Boot、MyBatis 或 JPA | 2~3 周 | 做出一个带数据库的增删改查 REST 服务 |
| 四 | 项目实战 + Spring Cloud 入门 | 4 周以上 | 独立完成一个可部署的完整项目 |
几点经验之谈:阶段三务必直接学 Spring Boot,不要从“XML + 部署 Tomcat”的老路走,2020 年之后的企业开发里 Spring Boot 已经是事实标准;数据库访问层选 MyBatis 入门更直观,想走通用路线就学 Spring Data JPA;每天稳定投入 2 小时的话,6 到 8 周可以达到“能写 Spring Boot 增删改查、能看懂别人项目”的水平。面试准备上,把 IoC 容器启动流程、Bean 生命周期、AOP 动态代理原理这三块讲透,就覆盖了初级岗位八成的考点。
常见问题
学Spring之前需要先学SSH(Struts2、Hibernate)吗?
不需要。SSH 是 2010 年前后的技术栈,Struts2 已基本淘汰,Hibernate 的思想已被 Spring Data JPA 吸收。直接从 Spring + Spring Boot 学起即可,省下的时间足够你多做一个完整项目。
Spring、Spring MVC、Spring Boot、Spring Cloud是一回事吗?
不是。Spring 是基础框架(IoC 容器 + AOP);Spring MVC 是它旗下的 Web 模块;Spring Boot 是在 Spring 之上做自动配置和脚手架封装,解决“配置地狱”问题;Spring Cloud 是微服务工具集。前三者是你入门的必经之路,Spring Cloud 等做完全项目再接触。
IoC和AOP是Spring发明的吗?
都不是。IoC 是一种设计思想(还有 EJB 容器实现了类似思想),AOP 是 1990 年代提出的编程范式,AspectJ 是其代表实现。Spring 是把这些思想落地最成功、门槛最低的开源框架,所以大家习惯把它们绑在一起学。
学Spring需要背住所有注解吗?
不用。Spring 注解有上百个,但日常开发高频的只有 20 个左右:@Configuration、@Bean、@Component/@Service/@Controller、@Autowired、@PostConstruct、@Transactional、@RequestMapping 等,其余用到时查文档即可,理解原理比背注解重要得多。
没有项目经验,只学完概念能找到工作吗?
单靠概念不够,但也不用先“全部学完”再找实习。建议阶段三结束时就把增删改查项目部署上线(租个便宜云服务器即可),项目里主动用上依赖注入、事务注解和 AOP 日志,这比任何背题都更有说服力。