一、Spring 框架概述 Spring 是一个轻量级的 Java 企业级开发框架,由 Rod Johnson 于 2003 年创建。它的核心使命是简化 Java 开发 。
Spring 生态 1 2 3 4 5 6 7 Spring Framework(核心) ├── Spring Boot(快速开发) ├── Spring Cloud(微服务) ├── Spring Data(数据访问) ├── Spring Security(安全) ├── Spring Batch(批处理) └── Spring WebFlux(响应式)
核心模块
模块
功能
Core Container
IoC 容器、Bean 管理
AOP
面向切面编程
Data Access
JDBC、ORM、事务管理
Web
Web MVC、WebSocket
Testing
单元测试、集成测试
二、IoC 容器 什么是 IoC IoC(Inversion of Control,控制反转) 是 Spring 的核心思想。传统开发中,对象的创建和依赖关系由开发者手动管理;IoC 将这个控制权交给 Spring 容器。
1 2 传统方式: 对象A → 主动创建 → 对象B IoC方式: 对象A ← 容器注入 ← 对象B
Bean 的定义 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @Component public class UserService { @Autowired private UserRepository userRepository; } @Configuration public class AppConfig { @Bean public DataSource dataSource () { return new HikariDataSource (); } }
常用注解
注解
说明
@Component
通用组件
@Service
业务层
@Repository
数据访问层
@Controller
控制层
@Configuration
配置类
@Bean
定义 Bean
@Autowired
自动注入
@Qualifier
按名称注入
@Value
注入配置值
Bean 的作用域 1 2 3 4 5 6 7 @Component @Scope("singleton") public class MyBean { }@Component @Scope("prototype") public class MyPrototypeBean { }
作用域
说明
singleton
默认,整个容器一个实例
prototype
每次请求新实例
request
每次 HTTP 请求一个实例
session
每个 HTTP Session 一个实例
Bean 的生命周期 1 2 3 4 5 6 7 8 1. 实例化(Instantiation) 2. 属性赋值(Populate properties) 3. BeanNameAware / BeanFactoryAware 4. BeanPostProcessor.postProcessBeforeInitialization 5. @PostConstruct / InitializingBean.afterPropertiesSet / init-method 6. BeanPostProcessor.postProcessAfterInitialization 7. 使用中... 8. @PreDestroy / DisposableBean.destroy / destroy-method
三、依赖注入(DI) 构造器注入(推荐) 1 2 3 4 5 6 7 8 9 10 11 @Service public class OrderService { private final UserService userService; private final PaymentService paymentService; public OrderService (UserService userService, PaymentService paymentService) { this .userService = userService; this .paymentService = paymentService; } }
Setter 注入 1 2 3 4 5 6 7 8 9 @Service public class NotificationService { private EmailSender emailSender; @Autowired public void setEmailSender (EmailSender emailSender) { this .emailSender = emailSender; } }
字段注入(不推荐) 1 2 3 4 5 @Service public class BadExample { @Autowired private SomeDependency dep; }
为什么推荐构造器注入
不可变性 :字段可以声明为 final
完整性 :保证依赖不为空
可测试性 :方便单元测试,不需要反射
明确性 :依赖一目了然
四、AOP(面向切面编程) 核心概念 1 2 3 4 切面(Aspect) = 切入点 + 通知 切入点(Pointcut) = 在哪里执行 通知(Advice) = 执行什么 连接点(JoinPoint)= 可能被拦截的点
通知类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 @Aspect @Component public class LogAspect { @Before("execution(* com.example.service.*.*(..))") public void before (JoinPoint jp) { System.out.println("Before: " + jp.getSignature().getName()); } @After("execution(* com.example.service.*.*(..))") public void after (JoinPoint jp) { System.out.println("After: " + jp.getSignature().getName()); } @AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result") public void afterReturning (Object result) { System.out.println("Return: " + result); } @AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "ex") public void afterThrowing (Exception ex) { System.out.println("Exception: " + ex.getMessage()); } @Around("execution(* com.example.service.*.*(..))") public Object around (ProceedingJoinPoint pjp) throws Throwable { long start = System.currentTimeMillis(); Object result = pjp.proceed(); long cost = System.currentTimeMillis() - start; System.out.println(pjp.getSignature().getName() + " cost: " + cost + "ms" ); return result; } }
切入点表达式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 execution(* com.example.service.*.*(..)) @annotation(com.example.annotation.Log) within(com.example.service.*) bean(userService) @Around("@annotation(log)") public Object aroundLog (ProceedingJoinPoint pjp, Log log) throws Throwable { }
自定义注解 + AOP 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface OperationLog { String value () default "" ; } @Aspect @Component public class OperationLogAspect { @Around("@annotation(opLog)") public Object log (ProceedingJoinPoint pjp, OperationLog opLog) throws Throwable { System.out.println("操作: " + opLog.value()); Object result = pjp.proceed(); return result; } }
五、事务管理 声明式事务 1 2 3 4 5 6 7 8 9 10 @Service public class AccountService { @Transactional public void transfer (Long fromId, Long toId, BigDecimal amount) { accountRepository.debit(fromId, amount); accountRepository.credit(toId, amount); } }
事务传播行为 1 2 3 4 5 6 7 @Transactional(propagation = Propagation.REQUIRED) @Transactional(propagation = Propagation.REQUIRES_NEW) @Transactional(propagation = Propagation.NESTED) @Transactional(propagation = Propagation.SUPPORTS) @Transactional(propagation = Propagation.NOT_SUPPORTED) @Transactional(propagation = Propagation.MANDATORY) @Transactional(propagation = Propagation.NEVER)
事务隔离级别 1 2 3 @Transactional(isolation = Isolation.READ_COMMITTED) @Transactional(isolation = Isolation.REPEATABLE_READ) @Transactional(isolation = Isolation.SERIALIZABLE)
隔离级别
脏读
不可重复读
幻读
READ_UNCOMMITTED
有
有
有
READ_COMMITTED
无
有
有
REPEATABLE_READ
无
无
有
SERIALIZABLE
无
无
无
回滚规则 1 2 3 4 5 6 7 8 9 10 11 @Transactional public void doSomething () { }@Transactional(rollbackFor = Exception.class) public void doSomething () throws Exception { }@Transactional(noRollbackFor = BusinessException.class) public void doSomething () { }
事务失效的常见场景
方法不是 public :Spring AOP 代理限制
自调用 :同类中方法调用不走代理
异常被 catch 吞掉 :事务感知不到异常
rollbackFor 配置不当 :默认只回滚 RuntimeException
数据库引擎不支持 :如 MyISAM 不支持事务
六、Spring MVC 请求处理流程 1 2 3 4 5 6 7 8 1. 客户端发送请求 2. DispatcherServlet 接收 3. HandlerMapping 查找 Handler 4. HandlerAdapter 执行 Handler 5. Controller 处理业务逻辑 6. 返回 ModelAndView 7. ViewResolver 解析视图 8. 渲染视图并返回响应
常用注解 1 2 3 4 5 6 7 8 9 10 11 12 13 14 @RestController @RequestMapping("/api") @GetMapping("/users") @PostMapping("/users") @PutMapping("/{id}") @DeleteMapping("/{id}") @PathVariable @RequestParam @RequestBody @RequestHeader @ExceptionHandler @ControllerAdvice
全局异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) public Result<?> handleBusiness(BusinessException e) { return Result.fail(e.getCode(), e.getMessage()); } @ExceptionHandler(Exception.class) public Result<?> handleException(Exception e) { log.error("系统异常" , e); return Result.fail(500 , "系统异常" ); } }
七、常用扩展点 BeanPostProcessor 1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Component public class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization (Object bean, String name) { return bean; } @Override public Object postProcessAfterInitialization (Object bean, String name) { return bean; } }
ApplicationListener 1 2 3 4 5 6 7 8 @Component public class StartupListener implements ApplicationListener <ContextRefreshedEvent> { @Override public void onApplicationEvent (ContextRefreshedEvent event) { System.out.println("Spring 容器初始化完成" ); } }
@EventListener 1 2 3 4 5 6 7 8 @Component public class OrderEventHandler { @EventListener public void onOrderCreated (OrderCreatedEvent event) { System.out.println("订单创建: " + event.getOrderId()); } }
总结 Spring 的核心是 IoC 容器和 AOP。理解 Bean 的生命周期、依赖注入方式、事务传播行为和 AOP 的工作原理,是掌握 Spring 的关键。这些知识不仅帮助正确使用 Spring,也是排查复杂问题的基础。