切面+自定义注解 实现无侵入加强操作

背景:在进行数据库操作前后,可能需要对数据进行校验或打印日志,为了减少重复代码,使用切面+自定义注解的方式处理

 

1.导入切面依赖

<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
</dependency>

 

如果是SpringBoot项目 导入Spring-aop注解也可  (笔者这里使用的是springboot的环境)

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

 

通过截图可知  aspectjweaver 依赖包含在 Spring-aop中

 

2.新建自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME) //运行时有效
@Target(ElementType.METHOD) //作用于方法
public @interface MyAnnotation {
}

 

3.编写切面类

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

@Aspect //切面类注解
@Component
public class advice {

    @Around(value = "@annotation(around)") //可以理解为传入annotation类型的变量,变量名around
    public void processAdvice(ProceedingJoinPoint point, MyAnnotation around) throws Throwable {
        System.out.println("start");  //模拟查询前执行的业务操作
        point.proceed();
        System.out.println("end");   //模拟查询后执行的业务操作
} }

 

4.在需要使用切面的方法处加上自定义注解

@RestController
public class Controller {

    @Autowired
    Service service;

    @GetMapping("getName")
    @MyAnnotation
    public List<User> getByName(){
        return service.getUser();  //查询数据库,获取对象
    }
}

 

效果如下,可以看到在查询日志的前后分别打印了“start”和“end” 这两个字符串

 

参考文章:https://blog.csdn.net/qq_41981107/article/details/85260765

 
posted @ 2022-02-08 17:53  CoderDinosaur  阅读(238)  评论(0编辑  收藏  举报