代码地址:https://github.com/hellboy0621/aop-ajc-demo.git

1. 实现 AspectJ 最简 Demo

先创建一个 SpringBoot 项目

创建需要增强的类和方法

@Service
public class MyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyService.class);

    public void foo() {
        LOGGER.info("foo()");
    }
}

创建切面

@Aspect
public class MyAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyAspect.class);

    @Before("execution(* com.xtransformers.service.MyService.foo())")
    public void before() {
        LOGGER.info("before()");
    }

}

在主类上获取逻辑对象并调用被增强的方法

@SpringBootApplication
public class AopAjcDemoApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(AopAjcDemoApplication.class);

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(AopAjcDemoApplication.class, args);

        MyService myService = context.getBean(MyService.class);
        LOGGER.info("MyService {}", myService.getClass());

        myService.foo();

        context.close();
    }
}

需要引入 AspectJ 依赖及 maven 插件

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.6</version>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>1.9.7</version>
</dependency>

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>aspectj-maven-plugin</artifactId>
  <version>1.14.0</version>
  <configuration>
    <complianceLevel>1.8</complianceLevel>
    <source>8</source>
    <target>8</target>
    <showWeaveInfo>true</showWeaveInfo>
    <verbose>true</verbose>
    <Xlint>ignore</Xlint>
    <encoding>UTF-8</encoding>
  </configuration>
  <executions>
    <execution>
      <goals>
        <goal>compile</goal>       <!-- use this goal to weave all your main classes -->
        <goal>test-compile</goal>  <!-- use this goal to weave all your test classes -->
      </goals>
    </execution>
  </executions>
</plugin>

日志打印

2022-04-16 09:56:02.747  INFO 12557 --- [           main] com.xtransformers.AopAjcDemoApplication  : MyService class com.xtransformers.service.MyService
2022-04-16 09:56:02.749  INFO 12557 --- [           main] com.xtransformers.aop.MyAspect           : before
2022-04-16 09:56:02.749  INFO 12557 --- [           main] com.xtransformers.service.MyService      : foo()

2. 实现原理

从日志中可以看到 MyService 没有被代理,也就是说使用 AspectJ 不是通过代理实现的。

打开 target 下生成的 class 文件