ex: Obtenha a idade do aluno ingressante, se for menor que 25 anos não será aprovado.
Principalmente dividido em duas etapas:
1. Anotações personalizadas
2.Interceptação de aspecto AOP
1. pom.xml introduz dependências relevantes
<!-- 引入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. Implemente anotações personalizadas (não explicarei as anotações específicas)
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 esta anotação
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. Crie um aspecto para interceptar a anotação.
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. Exibição de efeito