SpringAop小案例

一.我们需要添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

二. 创建一个切面类,并使用@Aspect和@Component注解修饰,在类里添加一个方法,这个方法就是你想要执行的方法.在方法上添加切入点,使用@Pointcut注解.

@Aspect
@Component
public class LogAspect {
    //注解表达式切入点
    @Pointcut("@annotation()")
    public void doLog(){}

}

三.自定义一个注解.

@Target(ElementType.METHOD)//注解可以加在哪里
@Retention(RetentionPolicy.RUNTIME)//注解合适生效
public @interface RequiredLog {
    String value() default "";
}

注解创建完成后,可以在切入点里加入这个注解所在的包路径,并添加一个通知.

@Slf4j
@Aspect
@Component
public class LogAspect {
    //注解表达式切入点
    @Pointcut("@annotation(com.jt.resource.annotation.RequiredLog)")
    public void doLog(){}//注解描述的方法

    
    @Around("doLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        log.debug("Before {}",System.currentTimeMillis());//{}表示占位符,
        Object result = joinPoint.proceed();//执行链(其他切面,目标方法)
        log.debug("After {}",System.currentTimeMillis());
        return result;//目标方法(切入点方法)的执行结果
    }

}

四. 最后在你需要添加的扩展业务的方法上添加自定义的注解,我这边是加载controller层的方法里面

//将RequiredLog注解描述的方法作为切入点方法,在方法执行之前和之后进行日志记录
    @RequiredLog("文件上传日志")//扩展业务--日志
    @PostMapping("/upload")//核心业务
    public String uploadFile(MultipartFile uploadFile) throws IOException {
        //1.创建文件存储目录(格式:yyyy/MM/dd)
        //ofPattern()方法设置格式,
        //1.1获取当前时间目录
        String dateDir = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        //1.2构建目录文件对象
        File uploadFileDir = new File(resourcePath,dateDir);
        if (!uploadFileDir.exists())uploadFileDir.mkdirs();

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值