只是一个简单的demo。。。。
1、pom文件
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.59</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、自定义注解
package com.example.aopdemo.aspect;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface CustomComment {
/**
* 默认为0 表示功能id在第一个参数位置上 , -1 表示未提供,无法进行校验
*/
int idx() default 0;
}
3、aop 切点
package com.example.aopdemo.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @author www
*/
@Aspect
@Component
public class CustomAspect {
static {
System.out.println("AuthAsprct测试静态代码块");
}
/**
*此处也可以使用@annotation(com.example.aopdemo.aspect.CustomComment)
*/
@Pointcut("execution(public * com.example.aopdemo.service.*.*(..))")
public void executeService(){
}
/**
* 01 . 前置通知:方法调用前被调用
*/
@Before("execution(public * com.example.aopdemo.service.*.*(..))")
public void before1(JoinPoint joinPoint){
System.out.println("进入before");
MethodSignature signature= (MethodSignature) joinPoint.getSignature();
Method method=signature.getMethod();
CustomComment autoAnno=method.getAnnotation(CustomComment.class);
if (autoAnno!=null){
//取出校验参数所在的位置
int idx=autoAnno.idx();
Object[] args=joinPoint.getArgs();
//取出需要校验的参数
int userId=(Integer)args[idx];
if(userId!=1){
System.out.println("访问接口失败");
}else{
System.out.println("访问接口成功");
}
}
}
}
3、service
package com.example.aopdemo.service;
import com.example.aopdemo.aspect.CustomComment;
import org.springframework.stereotype.Service;
/**
* @author www
*/
@Service
public class BuyService {
@CustomComment
public void byItem(int userId){
System.out.println("我要买东西:"+userId);
}
}
4、controller
@RequestMapping(value = "getStatus")
public void getStatus(){
buyService.byItem(1);
buyService.byItem(2);
}