SpringBoot —— AOP注解式拦截

一、首先我们添加添加aop依赖,此依赖已包含AspectJ相关依赖包。

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

二、编写拦截规则要拦截到的注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    String name() default "";
}

这里对元注解做个说明:元注解是指注解的注解,包括@Retention @Target @Document @Inherited四种。

五、编写切面

@Aspect
@Component
public class DataSourceAspect implements Ordered
{
    protected Logger logger = LoggerFactory.getLogger(getClass());
//
    @Pointcut("@annotation(com.unqd.ims.datasources.annotation.DataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DataSource ds = method.getAnnotation(DataSource.class);
        if(ds == null){
            DynamicDataSource.setDataSource("first");
            logger.debug("set datasource is " + "first");
        }else {
            DynamicDataSource.setDataSource(ds.name());
            logger.debug("set datasource is " + ds.name());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            logger.debug("clean datasource");
        }
    }

AOP注解说明:

@Aspect 定义切面:切面由切点和增强(引介)组成(可以包含多个切点和多个增强),它既包括了横切逻辑的定义,也包括了连接点的定义,SpringAOP就是负责实施切面的框架,它将切面所定义的横切逻辑织入到切面所指定的链接点中。
@Pointcut 定义切点:切点是一组连接点的集合。AOP通过“切点”定位特定的连接点。通过数据库查询的概念来理解切点和连接点的关系再适合不过了:连接点相当于数据库中的记录,而切点相当于查询条件。
@Before :在目标方法被调用之前做增强处理,@Before只需要指定切入点表达式即可。
@AfterReturning : 在目标方法正常完成后做增强,@AfterReturning除了指定切入点表达式后,还可以指定一个返回值形参名returning,代表目标方法的返回值。
@Afterthrowing: 主要用来处理程序中未处理的异常,@AfterThrowing除了指定切入点表达式后,还可以指定一个throwing的返回值形参名,可以通过该形参名来访问目标方法中所抛出的异常对象。
@After: 在目标方法完成之后做增强,无论目标方法时候成功完成。@After可以指定一个切入点表达式。
@Around: 环绕通知,在目标方法完成前后做增强处理,环绕通知是最重要的通知类型,像事务,日志等都是环绕通知,注意编程中核心是一个ProceedingJoinPoint。

发布了7 篇原创文章 · 获赞 12 · 访问量 1366

猜你喜欢

转载自blog.csdn.net/weixin_44919207/article/details/104901859