index.md 跨平台编程框架融码智汇 search
跨平台编程知识聚合站EDITOR · 跨平台编程笔记
</> 跨平台编程知识聚合站 Cross-Platform Dev
#893314 框架 2026.12.05 —

Java开发框架Spring学习 入门时总被IoC容器依赖注入和AOP绕晕 这份从环境搭建到Spring Boot实战的路线 按顺序讲清每个核心概念 让你少走弯路

DIR
框架
COMMIT
893314
DATE
12.05
UPDATE
12.05

学 Spring 入门绕晕,基本都卡在同一个地方:IoC 容器、依赖注入、AOP 这三个概念被教材拆成了三章分别讲,而它们其实是同一个问题的三面——IoC 是思想,依赖注入是实现方式,AOP 是同一思想在“横切逻辑”上的延伸。把这层窗户纸捅破,再按“环境搭建 → IoC/DI → AOP → Spring Boot 实战”的顺序走一遍,大多数困惑就自然消解了。这篇文章按这个顺序把每个核心概念讲透,所有代码都可直接复制运行。

Spring 到底是什么,为什么面试必问

Spring 是指一个开源的 Java 企业级开发框架,它的核心价值可以浓缩成一句话:通过 IoC(控制反转)容器管理对象的生命周期和依赖关系,让开发者把精力放在业务逻辑上,而不是 new 对象和拼装对象上。

很多初学者把 Spring 理解成“一个大工厂”,这个比喻方向对但不够准确。IoC 容器更像一个“管家”:你告诉它有哪些对象、对象之间谁依赖谁,它负责在程序运行时把这些对象创建好、组装好、随用随取。控制之所以叫“反转”,是因为对象创建的控制权从你的代码里反转到了容器手里——以前是你在代码里写 new UserServiceImpl(),现在由容器替你完成。

理解了这一点,依赖注入和 AOP 就好解释了:

  • 依赖注入(DI,Dependency Injection)是指容器在创建对象时,把它所依赖的其他对象主动“塞”进去,而不是让对象自己去获取依赖。Spring 支持构造器注入、Setter 注入、字段注入三种主流方式。
  • AOP(面向切面编程,Aspect-Oriented Programming)是指把一段与核心业务无关、但又分散在多个方法里的通用逻辑(比如日志、事务、权限校验)抽出来集中定义,由框架在运行时自动织入目标方法。

下面按学习顺序逐个落地。

环境搭建:从 JDK 到第一个能跑的 Spring 工程

版本怎么选才不踩坑

现在学 Spring 不要再碰 Spring 4 和 JDK 8 的老教程。2024 年之后的版本对应关系是:

你想学的东西 推荐版本 最低 JDK 要求
Spring Framework(核心) 6.1.x JDK 17
Spring Boot 3.2.x / 3.3.x JDK 17
构建工具 Maven 3.9+ 或 Gradle 8.x —

如果你的机器只有 JDK 8,要么升级 JDK(推荐 Temurin 17 或 21 LTS),要么去学 Spring Boot 2.x 老项目——但新学习一律建议从 3.x 起步,因为注解、Jakarta 命名空间(javax.* 已全部改为 jakarta.*)都是按新版生态写的。

Maven 依赖这样配

新建 Maven 工程,pom.xml 里先引入最精简的 Spring 核心包:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.1.10</version>
    </dependency>
</dependencies>

注意:只学 IoC 和依赖注入,spring-context 一个包就够了,不需要把 spring-core、spring-beans 全部手动声明,spring-context 会传递引入它们。依赖注入要用注解的话,再加上 spring-beans。

手写第一个 IoC 容器程序

先看没有 Spring 时怎么写,再对比就懂了。

// UserService.java —— 服务接口
public interface UserService {
    void sayHello();
}

// UserServiceImpl.java —— 服务实现
public class UserServiceImpl implements UserService {
    @Override
    public void sayHello() {
        System.out.println("你好,我是 UserService");
    }
}

// Main.java —— 传统写法
public class Main {
    public static void main(String[] args) {
        UserService service = new UserServiceImpl(); // 自己 new,自己控制
        service.sayHello();
    }
}

这种写法的问题在于:UserServiceImpl 一旦以后换成别的实现类,每个 new 的地方都得改,业务代码被实现细节绑死。换成 Spring 写法:

<!-- resources/beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- id 是容器里这个Bean的名字,class 是全限定类名 -->
    <bean id="userService" class="com.example.UserServiceImpl"/>
</beans>
// Main.java —— Spring 写法
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        // 容器启动时,会读取beans.xml并实例化里面声明的所有Bean
        ApplicationContext ctx =
                new ClassPathXmlApplicationContext("beans.xml");
        // 按类型从容器里取对象,容器里只有一个UserService实现
        UserService service = ctx.getBean(UserService.class);
        service.sayHello();
    }
}

运行输出:你好,我是 UserService。关键差别有两点:一是对象创建权交给了容器(IoC);二是你面向接口 UserService 取对象,将来换成 UserServiceImpl2 只需改 XML 一处,业务代码一行不动——这就是解耦。

依赖注入三种方式怎么选

IoC 容器管住了对象“怎么创建”,但对象之间的依赖关系怎么表达?这就用到了依赖注入。三种方式对比如下:

注入方式 写法 优点 缺点
构造器注入 在构造函数里接收依赖 强制依赖必填、不可变、利于测试 参数多时构造函数臃肿
Setter 注入 通过 setter 方法传入 依赖可选、可读性好 对象可能处于不完整状态
字段注入 @Autowired 直接标注字段 代码最简洁 无法声明不可变、不便于单元测试

实际项目里的推荐:首选构造器注入。Spring 官方文档和现在的最佳实践都倾向构造器注入,因为它能让依赖在对象构造完成后就是完整的,且单元测试时可以直接 new 出对象而不依赖容器。

构造器注入的完整示例

<!-- beans.xml:注意构造器注入用 <constructor-arg> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userRepository" class="com.example.UserRepositoryImpl"/>

    <!-- 容器创建userService时,发现它构造函数需要UserRepository,
         就自动把userRepository这个Bean塞进去 -->
    <bean id="userService" class="com.example.UserServiceImpl">
        <constructor-arg ref="userRepository"/>
    </bean>
</beans>
// UserServiceImpl.java
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository; // final:依赖不可变

    // 构造器注入:容器调用这个构造函数时传入依赖
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public void sayHello() {
        userRepository.findAll(); // 用的时候只管调,不用关心是谁实现的
    }
}

注解注入:开发效率的默认选择

XML 配置写多了很繁琐,注解把“声明”和“实现”放到了代码旁边:

@Repository // 标注数据访问层Bean
public class UserRepositoryImpl implements UserRepository { ... }

@Service // 标注业务层Bean
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;

    // @Autowired 告诉容器:这个构造参数请自动注入
    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}

要在 XML 里开启注解扫描,把 <context:component-scan base-package="com.example"/> 加进 beans.xml,容器就会扫描 com.example 包下所有带 @Component 家族注解(@Service、@Repository、@Controller)的类并注册成 Bean。现实项目中注解配置已占绝对主流,XML 配置现在主要出现在老项目维护里。

AOP 绕晕?先看一个没有 AOP 的痛点

假设你要给每个 Service 方法加日志:记录开始时间、打印入参、捕获异常。没有 AOP 时,你只能在每个方法里重复写这段代码——几十个方法就是几十段复制粘贴,一旦日志格式要改,就得改几十个地方。

AOP 的解法是:把日志逻辑抽到一个独立的“切面”类里,用“切点”声明它要拦截哪些方法,框架在运行时自动把你的日志代码织入这些方法。你完全不用改业务方法本身。

底层原理:JDK 动态代理

先花五分钟看透原理,AOP 的神秘感就没了。Spring AOP 默认对接口使用 JDK 动态代理,核心就三样东西:

// 1. 接口
public interface UserService {
    void sayHello();
}

// 2. 实现类:纯业务代码,不知道日志的存在
public class UserServiceImpl implements UserService {
    @Override
    public void sayHello() {
        System.out.println("执行 sayHello 业务逻辑");
    }
}

// 3. 代理处理器:织入日志逻辑
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class LogHandler implements InvocationHandler {
    private final Object target; // 目标对象(UserServiceImpl实例)

    public LogHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("【日志】方法 " + method.getName() + " 开始,入参:" + java.util.Arrays.toString(args));
        long start = System.currentTimeMillis();
        try {
            // 反射调用目标方法——业务逻辑在这里执行
            return method.invoke(target, args);
        } finally {
            System.out.println("【日志】方法 " + method.getName() + " 结束,耗时 " + (System.currentTimeMillis() - start) + "ms");
        }
    }
}

用的时候:

UserService realService = new UserServiceImpl();
// 动态生成一个代理对象,它实现了UserService接口,但内部委托给LogHandler
UserService proxy = (UserService) java.lang.reflect.Proxy.newProxyInstance(
        UserService.class.getClassLoader(),
        new Class[]{UserService.class},
        new LogHandler(realService));
proxy.sayHello(); // 调用的是代理对象,日志自动生效

运行后你会看到日志先于业务打印、耗时在业务后输出——而 UserServiceImpl 的源码里一行日志代码都没有。Spring AOP 做的事本质上就是这个动态代理的自动化版本:你声明切点,它替你生成代理对象。

Spring 声明式 AOP:@Aspect 实战

引入 spring-aop 和 aspectjweaver 依赖后,可以用注解写切面,工程里真正可用的写法:

import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect // 声明这是一个切面类
@Component // 注册成Bean,由容器管理
public class LogAspect {

    // 切点:拦截 com.example 下所有Service类的方法执行
    @Pointcut("execution(* com.example..*Service.*(..))")
    public void serviceMethods() {}

    // 前置通知:方法执行前自动跑这段代码
    @Before("serviceMethods()")
    public void logBefore() {
        System.out.println("【前置通知】即将执行Service方法");
    }

    // 环绕通知:能拿到方法入参,还能决定是否放行
    @Around("serviceMethods()")
    public Object logAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("【环绕通知】开始:" + pjp.getSignature().getName());
        long start = System.currentTimeMillis();
        try {
            return pjp.proceed(); // 放行,执行目标方法
        } finally {
            System.out.println("【环绕通知】结束,耗时:" + (System.currentTimeMillis() - start) + "ms");
        }
    }
}

三个注解各司其职:@Pointcut 定义“拦截谁”,@Before 是方法前自动执行的通知,@Around 环绕通知威力最大——它包裹整个方法,事务管理就是典型应用(方法进入时开事务、正常结束提交、抛异常回滚)。Spring 声明的切面与手写动态代理效果一致,但配置成本从几十行降到三个注解,这就是框架的价值。

Spring Boot 实战:十分钟跑通第一个接口

Spring Boot 是指 Spring 官方推出的脚手架,它通过“ starters(起步依赖)”把 Spring 生态里常用的依赖一次性引入,并内嵌 Tomcat,让你不用再写一行 XML 配置就能启动 Web 应用。注意:Spring Boot 不是替代 Spring,而是 Spring 的快速启动方式,IoC 和 AOP 的概念原封不动地继承了下来。

初始化项目

用 Spring Initializr(start.spring.io)生成,或手动建 Maven 项目,pom.xml 核心依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.5</version>
</parent>

<dependencies>
    <!-- Web起步依赖:内嵌Tomcat + Spring MVC + Jackson,一个包搞定 -->
    <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>

完整可运行代码

// UserApplication.java —— 启动类,@SpringBootApplication隐含开启组件扫描
@SpringBootApplication
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

// User.java —— 数据载体
public class User {
    private Long id;
    private String name;
    // 构造器、getter、setter省略
}

// UserRepository.java —— 数据访问层,@Repository注册成Bean
@Repository
public class UserRepository {
    public List<User> findAll() {
        List<User> list = new ArrayList<>();
        list.add(new User(1L, "张三"));
        list.add(new User(2L, "李四"));
        return list;
    }
}

// UserService.java —— 业务层,@Service注册成Bean
@Service
public class UserService {
    private final UserRepository userRepository;

    @Autowired // 构造器注入,容器自动把UserRepository塞进来
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> listUsers() {
        return userRepository.findAll();
    }
}

// UserController.java —— 控制层,@RestController返回JSON
@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping // GET /users 返回用户列表JSON
    public List<User> list() {
        return userService.listUsers();
    }
}

启动 UserApplication 后访问 http://localhost:8080/users,浏览器直接返回 [{"id":1,"name":"张三"},{"id":2,"name":"李四"}]。回看整个链路:Controller 依赖 Service、Service 依赖 Repository,全部由 IoC 容器注入,你从头到尾没写过一个 new UserService(...)——这就是依赖注入在真实项目里的样子。把前面写好的 LogAspect 放进这个项目(记得 @ComponentScan 能扫到它),所有 Service 方法就会自动带上日志,一个配置类都不用加。

学习路线与避坑清单

按这个顺序推进,每一步都有可验证的产出:

  1. 第 1 周:跑通第一个 XML 版 IoC 程序,理解 ApplicationContext 和 getBean;能说清“无 Spring 时 new 对象的耦合问题”即可。
  2. 第 2 周:掌握构造器注入,能手写一个三层依赖;理解 @ComponentScan 的扫描机制。
  3. 第 3 周:先手写 JDK 动态代理(20 行代码),再学 @Aspect 声明式 AOP;务必先懂代理再学注解,否则 AOP 永远是黑盒。
  4. 第 4 周起:用 Spring Boot 做一个小项目(待办事项、博客接口均可),把 IoC、DI、AOP 各用一遍。

几个高频坑提前说:javax.* 换 jakarta.* 导致的编译报错(Boot 3 特有);@Autowired 按类型注入时出现两个同类型 Bean 报 NoUniqueBeanDefinitionException,解决办法是加 @Primary 或 @Qualifier 指定名称;以及最常见的心态坑——以为看懂了教程等于掌握了,实际上必须动手把每个示例跑一遍、改一改、看报错,才算真正进入 Spring 的世界。

常见问题

Spring、Spring MVC、Spring Boot 三者有什么区别?

Spring 是 IoC/AOP 容器框架;Spring MVC 是 Spring 之上的 Web 层框架,负责处理 HTTP 请求;Spring Boot 是 Spring 全家桶的工程脚手架,内嵌服务器、自动配置 starter 依赖。三者是层层包含的协作关系,不是替代关系。

学 Spring 必须先学 MyBatis 或 JPA 吗?

不是。IoC 和 AOP 的核心概念与数据库技术无关,可以先独立学透 Spring 容器再接触持久层。但做实战项目时建议同步引入一个持久层框架,否则 Repository 层只能写假数据。

字段注入(@Autowired 标字段)和构造器注入到底用哪个?

生产项目推荐构造器注入:依赖不可变、对象构造后必然完整、单元测试无需容器即可 new 出对象。字段注入写起来最快,但依赖可能在对象构造后仍为 null,且不利于测试,属于“图省事”的选择。

Spring AOP 能拦截类的所有方法吗?

不能。默认只对满足切点表达式的方法生效,且只对 Spring 容器管理的 Bean 生效——new 出来的对象不在代理范围内。另外 Spring AOP 基于动态代理,对类内方法自调用(this.method())不生效,这是面试和实战中最高频的坑。

//

同目录笔记

Same Dir