了解掌握spring aop(下)

13 篇文章 0 订阅

      接着上一篇博客,日常开发中,经常能接触到注解这种东西,很多时候自定义注解可以和aop相结合,这里大概记录相应的用法,比方说我们有一个场景,和app端交互式,我们需要前端给出的请求信息进行校验,如果不用aop的话,可能很多人第一反应就是在Controller层去校验这些信息,但是从利用注解+aop机制我们会发现Controller层用一个注解就可以解决掉那些冗余的代码,省去那些繁琐的校验逻辑.

       假定一个需求,我们需要校验用户名的名字不能大于6个字符,年龄需要大于18岁,下面写一下相应的校验逻辑。

       这里扩展一下注解的一些常见属性

@Documented:  Javadoc 生成使用

@Inherited     拥有继承性

@Target         这个注解被应用到哪里,这里是应用到Controller的方法上面

@Retention   当值被设置成runtime的时候,表示运行期类型被定义,并被jvm所读取

package com.mimoprint.schedule.annotation;

import java.lang.annotation.*;

@Documented
@Inherited
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserCheck {

    //是否需要校验
    boolean needCheck() default true;
}

  aop部分代码:

package com.mimoprint.schedule.aop;

import com.mimoprint.schedule.annotation.UserCheck;
import com.mimoprint.schedule.model.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Slf4j
@Component
public class UserAspect {



    @Around("execution(* com.mimoprint..*Controller.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取连接点的方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取相对应的方法
        Method method = signature.getMethod();
        //从接口中获取注解,如果是我们自定义的注解,就开始进行判断
        UserCheck userCheck = method.getAnnotation(UserCheck.class);
        if (userCheck != null && userCheck.needCheck()) {
            Object[] paramters = joinPoint.getArgs();
            for (Object paramter : paramters) {
                if (paramter instanceof User) {
                    User user = (User) paramter;
                    int age = user.getAge();
                    String username = user.getUsername();
                    if (age < 18 || username.length() < 6) {
                        throw new RuntimeException("*****校验异常*****");
                    }
                }
            }
        }
        return joinPoint.proceed();
    }

}

   controller部分代码:

 

    @PostMapping("/testAnnotation")
    @UserCheck(needCheck = true)
    public RestResult testAnnotation(User user) {
        return new RestResult(200, "success", user);
    }

结果:

http://localhost:9001/api/testAnnotation?username=roadsides&age=23

{
    "code": 200,
    "message": "success",
    "entity": {
        "username": "roadsides",
        "age": 23
    }
}

不满足的时候:

{
    "timestamp": "2018-12-30T13:09:19.285+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "*****校验异常*****",
    "path": "/api/testAnnotation"
}

      这里需要注意一点,如果做环绕切面的时候,用到了ProceedingJoinPoint,记得一定要返回joinPoint.proceed() ,不然会有出现很奇怪的现象,明明校验通过了,但是前段接受不到任何返回值,因为aop切面其实并没有接收到完整的通过标记,所以整个流程没有完全走完,这里也是一个坑,在这里mark一下,以后有空的时候在整理一下其他常见的aop用法吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值