spring-aop-@Aspect详细用法

本文详细介绍了SpringAOP中AspectJ的使用方法,包括常见的切入点表达式及增强方式,如@Before、@AfterReturning等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@AspectJ的详细用法
在Spring AOP中目前只有执行方法这一个连接点,Spring AOP支持的AspectJ切入点指示符如下:

一些常见的切入点的例子
execution(public * * (. .)) 任意公共方法被执行时,执行切入点函数。
execution( * set* (. .)) 任何以一个“set”开始的方法被执行时,执行切入点函数。
execution( * com.demo.service.AccountService.* (. .)) 当接口AccountService 中的任意方法被执行时,执行切入点函数。
execution( * com.demo.service.. (. .)) 当service 包中的任意方法被执行时,执行切入点函数。 within(com.demo.service.) 在service 包里的任意连接点。 within(com.demo.service. .) 在service 包或子包的任意连接点。
this(com.demo.service.AccountService) 实现了AccountService 接口的代理对象的任意连接点。
target(com.demo.service.AccountService) 实现了AccountService 接口的目标对象的任意连接点。
args(java.io.Serializable) 任何一个只接受一个参数,且在运行时传入参数实现了 Serializable 接口的连接点
增强的方式:
@Before:方法前执行
@AfterReturning:运行方法后执行
@AfterThrowing:Throw后执行
@After:无论方法以何种方式结束,都会执行(类似于finally)
@Around:环绕执行

Spring AOP 中启用 @Aspect 注解,你需要在以下几个步骤中操作: 1. **添加依赖**:确保你的项目依赖了 Spring AOP 相关的库,例如在 Maven 项目的 `pom.xml` 文件中添加 `<spring-aop>` 或 `<aop:aspectj-autoproxy>` 标签。 ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> ``` 或者对于基于 XML 配置的方式: ```xml <aop:config> <!-- 其他配置 --> <aop:aspect id="myAspect" ref="com.example.MyAspect"> <!-- aspect 类路径 --> </aop:aspect> </aop:config> ``` 2. **编写 @Aspect 类**:创建一个实现了 `@Aspect` 注解的 Java 类,该类中包含 `@Before`、`@After`、`@Around` 等通知注解的切入点方法。 ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect @Component public class MyAspect { @Before("execution(* com.example.service.MyService.*(..))") public void beforeAdvice(JoinPoint joinPoint) { // 执行前的操作 } } ``` 3. **配置扫描**:在 Spring 的配置文件中,使用 `@ComponentScan` 或者 `<context:component-scan>` 注入 `@Aspect` 注解的类。 ```xml <context:component-scan base-package="com.example"> <!-- 如果需要扫描特定包中的 aspects --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> ``` 4. **启动应用**:启动 Spring 应用,这时 Spring AOP 就会处理包含 @Aspect 注解的切面。 现在,你应该可以在目标类(如 service 层)中的方法上看到切面的通知效果了。如果你仍然遇到问题,可以检查配置文件、依赖及代码逻辑,看看是否有其他冲突或者遗漏的地方。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绿竹痕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值