在Java中实现AOP(面向切面编程)主要有两种方式:使用Spring框架的AOP功能和使用AspectJ。下面分别给出这两种方式的示例代码。
一、使用Spring AOP
<dependencies>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.23</version>
</dependency>
<!-- Spring Context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.23</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
</dependencies>
1.添加依赖
首先,需要在项目的`pom.xml`文件中添加Spring AOP相关的依赖:
package com.example.demo;
import org.springframework.stereotype.Component;
@Component
public class BusinessService {
public void doSomething() {
System.out.println("BusinessService.doSomething() is running");
}
}
2.创建业务逻辑类
package com.example.demo;
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.demo.BusinessService.doSomething(..))")
public void beforeAdvice() {
System.out.println("Before advice is running");
}
}
3.创建切面类
4.配置Spring容器并测试
package com.example.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext("com.example.demo");
BusinessService businessService = context.getBean(BusinessService.class);
businessService.doSomething();
}
}
运行上述代码,输出结果如下:
Before advice is running
BusinessService.doSomething() is running
二、使用AspectJ
1.添加依赖
在`pom.xml`文件中添加AspectJ的依赖:
2.创建业务逻辑类
3.创建切面类
4.配置AspectJ织入器并测试
由于AspectJ的织入方式与Spring AOP有所不同,这里以编译时织入(使用ajc编译器)为例进行说明。首先,需要将业务逻辑类和切面类编译成class文件,然后使用ajc命令进行织入:
最后,编写测试代码:
运行上述代码,输出结果如下:
以上就是使用Spring AOP和AspectJ实现AOP的具体代码示例。你可以根据实际项目需求选择合适的实现方式。