刚学 Spring 被 IoC、AOP 这些缩写绕晕,其实很正常——问题不在于你学不会,而在于大多数教程一上来就讲概念,把人讲懵了。正确的上手顺序是:先搭建环境,再写依赖注入,最后实操 AOP,按这条线走,零基础也能在几个小时内做出第一个能跑的 Spring 小项目。Spring 是一个开源的 Java 企业级开发框架,它的核心思想只有两个:IoC(控制反转)负责帮你管理对象之间的依赖关系,AOP(面向切面编程)负责把日志、事务这类“横切逻辑”从业务代码里抽出来。下面按真实的学习路径,一步步带你走。
Spring 入门先搞懂两件事:IoC 和 AOP 到底指什么
IoC 是什么?用一句大白话讲透
IoC(Inversion of Control,控制反转)是指:对象不再自己创建和管理所依赖的其他对象,而是把这个权力交给 Spring 容器统一管理。
打个比方:以前你在代码里要写 UserRepository repo = new UserRepositoryImpl(),对象之间是“手拉手”硬连的;用了 IoC 之后,你只需要声明“我需要一个 UserRepository”,Spring 容器会帮你把实现类实例找出来、塞进去。这个“被 Spring 塞进来”的过程,就是依赖注入(DI,Dependency Injection),它是 IoC 最主要的实现方式。
AOP 是什么?为什么需要它
AOP(Aspect-Oriented Programming,面向切面编程是指:把一段与业务无关、但多个地方都要用的逻辑(如日志、权限校验、性能统计)集中写在一个地方,通过配置在运行时自动织入到目标方法上。
举个真实场景:你写了 20 个 Service 方法,每个方法开头都要打印一行日志。如果没有 AOP,你得在 20 个方法里各写一遍日志代码;有了 AOP,你在切面类里写一次规则,Spring 会自动在所有匹配的方法执行前后加上日志。IoC 解决的是“对象谁来创建”的问题,AOP 解决的是“重复代码放哪”的问题——两个概念服务的方向不同,别混着记。
| 概念 | 一句话理解 | 典型应用场景 |
|---|---|---|
| IoC | 对象交给 Spring 容器统一管理 | Bean 的创建和依赖关系维护 |
| 依赖注入(DI) | IoC 的具体实现方式 | 构造器注入、Setter 注入、字段注入 |
| AOP | 横切逻辑集中管理、自动织入 | 日志、事务、权限、监控 |
Spring 环境搭建:从 JDK 到 Maven 的每一步
第一步:确认 JDK 版本
新手最常见的坑是版本不匹配。Spring 5.3.x 支持 JDK 8 到 JDK 19,Spring 6.x 则强制要求 JDK 17 及以上。零基础建议用 JDK 8 + Spring 5.3.x,资料最多、报错最少。在终端输入 java -version 确认,如果没装,去 Oracle 或 Adoptium 官网下载对应版本即可。
第二步:创建 Maven 项目并引入依赖
Maven 是 Java 的依赖管理工具,它负责把 Spring 的 jar 包下载到你本地。新建一个 Maven 项目后,在 pom.xml 中加入以下三个核心依赖:
<dependencies>
<!-- IoC 容器核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.30</version>
</dependency>
<!-- AOP 功能支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.30</version>
</dependency>
<!-- AspectJ 切点表达式解析库 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.20.1</version>
</dependency>
</dependencies>
三个依赖的作用分别是:spring-context 提供 IoC 容器能力,spring-aop 提供 AOP 框架支持,aspectjweaver 用来解析切点表达式。少任何一个,AOP 切面都不会生效,这是新手最容易漏的地方。
第三步:写一个配置类
Spring 传统上用 XML 配置,但现在更推荐注解配置。创建 AppConfig.java:
package com.example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration // 声明这是一个 Spring 配置类
@ComponentScan("com.example") // 告诉 Spring 去 com.example 包下扫描组件
@EnableAspectJAutoProxy // 开启 AOP 代理功能,必须加这一行
public class AppConfig {
}
三个注解的作用:@Configuration 标记这是配置类,@ComponentScan 指定扫描包范围(你的业务类都在这个包下才会被 Spring 管理),@EnableAspectJAutoProxy 开启 AOP 支持——漏了这行,切面代码写了也不会执行。
依赖注入实操:三种注入方式怎么选
先搭一个能跑的业务骨架
我们模拟一个“查用户”的小场景。创建实体类 User:
package com.example.entity;
public class User {
private String name;
private Integer age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
@Override
public String toString() {
return "User{name='" + name + "', age=" + age + "}";
}
}
再写数据访问层接口和实现:
package com.example.repository;
import com.example.entity.User;
public interface UserRepository {
User findById(Long id);
}
package com.example.repository;
import com.example.entity.User;
import org.springframework.stereotype.Repository;
@Repository // 告诉 Spring:这个类交给容器管理,名字叫 userRepository
public class UserRepositoryImpl implements UserRepository {
@Override
public User findById(Long id) {
System.out.println("模拟从数据库查询 id=" + id);
User user = new User();
user.setName("张三");
user.setAge(25);
return user;
}
}
三种注入方式,写法对比
Service 层依赖 Repository,注入方式有三种,写法如下:
package com.example.service;
import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
// 方式一:字段注入(最常见,但最不推荐)
@Autowired
private UserRepository userRepository;
// 方式二:构造器注入(推荐写法)
private final UserRepository repositoryByConstructor;
public UserServiceImpl(UserRepository repositoryByConstructor) {
this.repositoryByConstructor = repositoryByConstructor;
}
@Override
public User getUser(Long id) {
return userRepository.findById(id);
}
}
三种方式怎么选?给个明确结论:
| 注入方式 | 写法 | 优点 | 缺点 | 推荐场景 |
|---|---|---|---|---|
| 构造器注入 | 构造函数传参 | 依赖不可变、便于测试、必填依赖不会漏 | 依赖多时代码啰嗦 | 首选,Spring 官方推荐 |
| Setter 注入 | setter 方法传参 | 可选依赖灵活 | 依赖可能没设置就报错 | 可选依赖场景 |
| 字段注入 | @Autowired 标注字段 |
代码最简洁 | 无法声明不可变、不便于单测 | 快速原型、学习演示 |
我的建议:学习阶段三种都写一遍理解原理,实际项目优先用构造器注入。 字段注入虽然简单,但对象创建后依赖可能被人为置空,且无法写单元测试替换依赖,是面试和团队规范里常被批评的写法。
AOP 实操:给方法加上日志切面
写一个日志切面
AOP 的核心是切面类。创建 LogAspect.java:
package com.example.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 // 交给 Spring 容器管理
public class LogAspect {
// 切点规则:匹配 com.example.service 包下所有类的所有方法
@Before("execution(* com.example.service..*.*(..))")
public void beforeLog(JoinPoint joinPoint) {
System.out.println("[日志] 即将调用方法:" + joinPoint.getSignature().getName());
}
@AfterReturning(
pointcut = "execution(* com.example.service..*.*(..))",
returning = "result"
)
public void afterLog(JoinPoint joinPoint, Object result) {
System.out.println("[日志] 方法 "
+ joinPoint.getSignature().getName()
+ " 执行完毕,返回值:" + result);
}
}
逐段解释:@Aspect 和 @Component 缺一不可,前者告诉 Spring“这是个切面”,后者让切面本身也被容器管理;@Before 里的 execution(* com.example.service..*.*(..)) 是切点表达式,* 表示任意返回值和任意参数,.. 表示任意多层子包和任意参数列表,意思是“service 包下所有类的所有方法”。@AfterReturning 的 returning = "result" 把方法返回值绑定到参数上,方便打印。
一个必须知道的关键点:AOP 只对 Spring 容器里的 Bean 生效
如果 UserServiceImpl 没有加 @Service 注解,Spring 容器管不到它,切面就不会生效。AOP 的本质是代理对象:Spring 会在运行时为你的 Service 生成一个代理类,调用方法时代理类先执行切面逻辑,再调用真实方法。所以自己 new 出来的对象,测试 AOP 是测不到的。
拼起来跑:第一个 Spring 小项目完整流程
项目结构
src/main/java/com/example
├── AppConfig.java // 配置类
├── Main.java // 启动类
├── aspect/LogAspect.java // AOP 切面
├── entity/User.java // 实体类
├── repository/UserRepository.java // 接口
├── repository/UserRepositoryImpl.java // 实现类
└── service/UserService.java // 接口
service/UserServiceImpl.java // 实现类
启动类
package com.example;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
// 用配置类启动 Spring 容器
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
// 从容器里获取 UserService(IoC 的体现)
UserService userService = context.getBean(UserService.class);
// 调用方法,AOP 的日志切面会自动执行
User user = userService.getUser(1L);
System.out.println("最终结果:" + user);
context.close();
}
}
运行 Main,控制台输出:
[日志] 即将调用方法:getUser
模拟从数据库查询 id=1
[日志] 方法 getUser 执行完毕,返回值:User{name='张三', age=25}
最终结果:User{name='张三', age=25}
注意看:Service 里没有写一行日志代码,但方法调用前后自动打印了日志——这就是 AOP 的威力。到这里,IoC(容器管理对象)、依赖注入(Service 自动拿到 Repository)、AOP(切面自动织入日志)三件事全部串起来了。
新手最容易踩的 4 个坑
- 依赖版本冲突:Spring 相关依赖版本必须一致,
spring-context、spring-aop用同一个版本号,否则启动报NoSuchMethodError。 - 忘了
@EnableAspectJAutoProxy:切面类写得再对,不加这行注解,AOP 完全不生效,且不报任何错,最难排查。 - 扫描包写错:
@ComponentScan("com.example")写成了com.example.service,Repository 没被扫描到,启动时报NoSuchBeanDefinitionException。 - 自己 new 对象绕过容器:在 Main 里写
new UserServiceImpl()而不是context.getBean(),依赖注入和 AOP 全部失效,因为容器根本没参与对象创建。
常见问题
Spring 的 IoC 和 DI 是一回事吗?
不是。IoC 是“控制权交给容器”这个思想,DI(Dependency Injection,依赖注入)是实现 IoC 的具体手段。IoC 是目的,DI 是手段,日常开发里说“Spring 的 IoC”通常就是指依赖注入。
AOP 和设计模式里的代理模式有什么关系?
AOP 底层就是动态代理。Spring 默认用 JDK 动态代理(接口存在时),目标类没有接口时用 CGLIB 代理(生成子类)。理解代理模式后,AOP 的“织入”过程就很好懂了:代理对象拦截方法调用,插入切面逻辑。
一个 Spring 项目最少需要几个依赖?
纯 IoC 只需 spring-context 一个依赖;如果要 AOP,再加 spring-aop 和 aspectjweaver 两个,总共三个。这三个是零基础入门 Spring 的最小集合。
学完 IoC 和 AOP 之后下一步学什么?
建议按这个顺序:事务管理(@Transactional)→ Spring MVC(写 REST 接口)→ MyBatis 或 JPA(操作数据库)。IoC 和 AOP 是 Spring 的地基,地基打牢了,后面的学习会顺很多。