aop实战简单快速

步骤

1. 导入依赖:在pom.xml中导入AOP的依赖

2. 编写AOP程序:针对于特定方法根据业务需要进行编程

pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@Component
@Aspect //当前类为切面类
public class TimeAspect {
@Around("execution(* com.itheima.service.*.*(..))")
public Object recordTime(ProceedingJoinPoint pjp) throws
Throwable {
//记录方法执行开始时间
long begin = System.currentTimeMillis();
//执行原始方法
Object result = pjp.proceed();
//记录方法执行结束时间
long end = System.currentTimeMillis();
//计算方法执行耗时
log.info(pjp.getSignature()+"执行耗时: {}毫秒",end-begin);
return result;
}
}

就可以计算出调用这个方法所需要的时间了。

execution

这里主要说明一下execution表达式

execution(访问修饰符? 返回值 包名.类名.?方法名(方法参数) throws 异常?)

其中带 ? 的表示可以省略的部分
访问修饰符:可省略(比如: public、protected)
包名.类名: 可省略
throws 异常:可省略(注意是方法上声明抛出的异常,不是实际抛出的异常)。

示例:

@Before("execution(void
com.itheima.service.impl.DeptServiceImpl.delete(java.lang.Integer))")。

切入点表达式的语法规则:
1. 方法的访问修饰符可以省略
2. 返回值可以使用 * 号代替(任意返回值类型)
3. 包名可以使用 * 号代替,代表任意包(一层包使用一个 * )
4. 使用 .. 配置包名,标识此包以及此包下的所有子包
5. 类名可以使用 * 号代替,标识任意类
6. 方法名可以使用 * 号代替,表示任意方法
7. 可以使用 * 配置参数,一个任意类型的参数
8. 可以使用 .. 配置参数,任意个任意类型的参数

@annotation另一种切入点表达式

实现步骤:
1. 编写自定义注解
2. 在业务类要做为连接点的方法上添加自定义注解

自定义注解:MyLog

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
}

然后就在业务层的方法上面加上@Mylog注解就标记了

切面类

@Aspect
public class LogAspect {
    
    @Around("@annotation(com.itheima.utils.MyLog)")
    public Object recordLog(ProceedingJoinPoint point) throws Throwable {


                中间略过。。。。
       
    }

}

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值