Spring AOP(面向切面编程)是一种强大的工具,可以让你在不修改现有代码的情况下增加额外的行为。例如,你可以使用AOP来添加日志记录、性能监控、事务管理等功能。
Spring AOP的核心是"切面"(Aspect),它定义了跨越系统多个模块的横切关注点。Spring AOP基于代理模式实现,主要支持两种方式的代理:JDK动态代理和CGLIB代理。
下面是一个简单的Spring AOP示例,使用AspectJ注解来创建切面:
- 添加依赖(Maven示例):
 
<dependencies>
    <!-- Spring AOP -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
</dependencies>- 创建一个切面:
 
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
 
@Aspect
@Component
public class MyAspect {
 
    @Before("execution(* com.example.service.*.*(..))")
    public void beforeMethod() {
        System.out.println("Before method execution");
    }
}- 服务类和接口:
 
package com.example.service;
 
public interface MyService {
    void someServiceMethod();
}
package com.example.service;
 
import org.springframework.stereotype.Service;
 
@Service
public class MyServiceImpl implements MyService {
    @Override
    public void someServiceMethod() {
        System.out.println("Service method executed");
    }
}- 配置类启用AspectJ支持:
 
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}- 应用主类:
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
        MyService myService = context.getBean(MyService.class);
        myService.someServiceMethod();
        context.close();
    }
}执行Application类的main方法,你会看到在调用someServiceMethod之前,MyAspect中的beforeMethod会被执行,这说明Spring AOP已经生效。这个简单的例子展示了如何在调用MyService的任何方法之前,执行一些额外的逻辑(例如日志记录)。