1. 背景
在现代软件开发中,面向切面编程(AOP
)是一种强大的编程范式,允许开发者跨越应用程序的多个部分定义横切关注点(如日志记录、事务管理等)。本文将介绍如何在Spring
框架中通过AspectJ
注解以及对应的XML
配置来实现AOP
,在不改变主业务逻辑的情况下增强应用程序的功能。
2. 基于 AspectJ 注解来实现 AOP
对于一个使用Maven
的Spring
项目,需要在pom.xml
中添加以下依赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
复制代码
确保版本号与使用的Spring
版本相匹配,可以自行调整。
-
创建业务逻辑接口 MyService:
package com.example.demo.aop;
public interface MyService {
void performAction();
}
复制代码
-
创建业务逻辑类 MyServiceImpl.java:
package com.example.demo.aop;
import org.springframework.stereotype.Service;
@Service
public class MyServiceImpl implements MyService {
@Override
public void performAction() {
System.out.println("Performing an action in MyService");
}
}
复制代码
-
定义切面
创建切面类MyAspect.java
,并使用注解定义切面和通知:
package com.example.demo.aop;
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.aop.MyServiceImpl.performAction(..))")
public void logBeforeAction() {
System.out.println("Before performing action");
}
}
复制代码
@Aspect
注解是用来标识一个类作为AspectJ
切面的一种方式,这在基于注解的AOP
配置中是必需的。它相当于XML
配置中定义切面的方式,但使用注解可以更加直观和便捷地在类级别上声明切面,而无需繁琐的XML
配置。
-
配置 Spring 以启用注解和 AOP
创建一个Java
配置类来代替XML
配置,使用@Configuration
注解标记为配置类,并通过@ComponentScan
注解来启用组件扫描,通过@EnableAspectJAutoProxy
启用AspectJ
自动代理:
package com.example.demo.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
public class AppConfig {
}
复制代码
@EnableAspectJAutoProxy
注解在Spring
中用于启用对AspectJ
风格的切面的支持。它告诉Spring
框架去寻找带有@Aspect
注解的类,并将它们注册为Spring
应用上下文中的切面,以便在运行时通过代理方式应用这些切面定义的通知(Advice
)和切点(Pointcuts
)。
如果不写@EnableAspectJAutoProxy
,Spring
将不会自动处理@Aspect
注解定义的切面,则定义的那些前置通知(@Before
)、后置通知(@After
、@AfterReturning
、@AfterThrowing
)和环绕通知(@Around
)将不会被自动应用到目标方法上。这意味着定义的AOP
逻辑不会被执行,失去了AOP
带来的功能增强。
@Before
注解定义了一个前置通知(Advice
),它会在指定方法执行之前运行。切点表达式execution(* com.example.demo.aop.MyServiceImpl.performAction(..))
精确地定义了这些连接点的位置。在这个例子中,切点表达式指定了