springboot uses custom annotations to verify incoming parameters

eg: Get the age of the incoming student. If it is less than 25, it will not pass. 

Mainly divided into two steps:

             1. Custom annotations

              2.AOP aspect interception

1. pom.xml introduces relevant dependencies

        <!-- 引入aop 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!-- aspect 依赖  -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.6</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.27</version>
        </dependency>

2. Implement customized annotations (I won’t explain the specific annotations)

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented  //-- 生成javadoc 文档
// @Inherited  --子类拥有父类的注解 @Inherited注解只对那些@Target被定义为ElementType.TYPE的自定义注解起作用。
public @interface StudentAnnotion {

    String name() ;
    int age() default 18;

}

3. Use this annotation

import com.bfy.demo.annotation.StudentAnnotion;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试注解
 */
@RestController
public class TestAnnotationController {

    @RequestMapping( value = "man")
    @StudentAnnotion(name = "莉莉",age = 25)  
    public String firstTest (@RequestParam  String name,@RequestParam int age ) {
        return name + age;
    }


}

4. Create an aspect to intercept the annotation.

import com.bfy.demo.annotation.StudentAnnotion;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class StudentAnnotionspect {

    @Pointcut("@annotation(com.bfy.demo.annotation.StudentAnnotion)")  // 切入点 为该注解
    private void pointcut() {
    }

    @Around("pointcut() &&  @annotation(studentAnnotion) ")
    public Object around(ProceedingJoinPoint joinPoint, StudentAnnotion studentAnnotion) throws Throwable {

        // 获取传递参数
        Object[] args = joinPoint.getArgs();
        Integer age = (Integer) args[1];
        if (studentAnnotion.age() > age) {
            return "年纪太小";
        }
        return joinPoint.proceed();
    }

}

5. Effect display

suitable         

Guess you like

Origin blog.csdn.net/bfy0914/article/details/102507985