在Spring AOP中,使用两个或多个切面类的组合是非常常见的使用方式。这种能让咱们将不同的关注点分离到不同的切面中,从而实现更高的模块化和可维护性
示例:假设我们有两个切面:LoggingAspect 和 TransactionAspect,分别用于记录日志和处理事务。
文章目录
1. 定义切面类
LoggingAspect:记录方法调用的日志
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
@Aspect
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before method: " + joinPoint.getSignature().getName());
}
@After("execution(* com.example.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("After method: " + joinPoint.getSignature().getName());
}
}
TransactionAspect:处理事务
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
@Aspect
public class TransactionAspect {
@Before("execution(* com.example.service.*.*(..))")
public void beginTransaction() {
System.out.println("Beginning transaction");
// 开始事务的逻辑
}
@After("execution(* com.example.service.*.*(..))")
public void commitTransaction() {
System.out.println("Committing transaction");
// 提交事务的逻辑
}
}
2. 配置切面
在Spring配置中,需要将这些切面声明为Spring的bean,并启用AspectJ自动代理。
Spring配置文件(XML配置):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- Enable AspectJ auto proxying -->
<aop:aspectj-autoproxy />
<!-- Define the LoggingAspect bean -->
<bean id="loggingAspect" class="com.example.aspect.LoggingAspect" />
<!-- Define the TransactionAspect bean -->
<bean id="transactionAspect" class="com.example.aspect.TransactionAspect" />
</beans>
Spring配置类(Java配置):
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
@Bean
public LoggingAspect loggingAspect() {
return new LoggingAspect();
}
@Bean
public TransactionAspect transactionAspect() {
return new TransactionAspect();
}
}
标签:AOP,annotation,切面,org,SpringAOP,import,public,aspectj
From: https://blog.csdn.net/qq_61905492/article/details/141645006