# Spring AOP

# Spring AOP

AOP:面向切面编程

注意:AOP并不是Spring原创的技术,也不是Spring的独家技术,而是源自AspectJ,只是Spring很好的支持了AOP。

AOP技术主要解决了“横切关注”的相关问题,也就是“若干个不同的方法都需要执行相同的任务”的问题!

在许多框架中,都通过AOP技术实现了对应的功能,例如:

- 在Spring JDBC中,使用AOP实现了事务管理

  ```
  try {
      开启事务
      执行连接点:你的业务方法
      提交事务
  } catch (RuntimeException e) {
      回滚事务
  }
 

- 在Spring MVC框架中,使用AOP处理了异常

- 在Spring Security框架,使用AOP检查权限

假设存在需求:统计当前项目中所有Service方法的执行耗时。

在Spring Boot项目中使用AOP需要添加依赖:

```xml
<!-- Spring Boot支持AOP的依赖项 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
```

```java
package cn.tedu.tea.admin.server.core.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 统计所有Service方法执行耗时的切面类
 *
 * @author java@tedu.cn
 * @version 1.0
 */
@Aspect
@Component
public class TimerAspect {

    @Around("execution(* cn.tedu.tea.admin.server..service.*.*(..))")
    public Object xx(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object proceedResult = pjp.proceed();
        long end = System.currentTimeMillis();
        System.out.println("执行耗时:" + (end - start));
        return proceedResult;
    }

}
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值