此处就不解释AOP到底能做什么的了。废话不多说,直接上代码,看效果
定义一个注解
@Target(ElementType.METHOD) //使用位置(类,方法)
@Retention(RetentionPolicy.RUNTIME) //加载到jvm里运行
@Documented
public @interface MyAnnotation {
String name() default "";//属性,默认值""
int age() default 23;//属性,默认值23
}
实现这个注解分析类
import io.renren.common.annotation.MyAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
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;
@Aspect //定义一个切面
@Component
public class MyAnnotationAspect {
//定义切点,路径为注解的路径
@Pointcut("@annotation(io.renren.common.annotation.MyAnnotation)")
public void myPointCut(){
}
@Before("myPointCut()")
public void MyBeforCut(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String methodName = method.getName();//获取执行方法名
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
if(null != myAnnotation){
//获取注解参数值
System.out.println("===========获取注解参数值==========");
System.out.println("age= "+myAnnotation.age());
System.out.println("name= "+myAnnotation.name());
System.out.println("===========获取注解参数值==========");
}
//获取方法传递的参数
Object[] args = joinPoint.getArgs();
if(null != args){
for(Object o : args){
System.out.println("方法传递的参数: "+ o.toString());
}
}
System.out.println("==============MyBeforCut方法,执行接口【"+methodName+"】之前触发=============");
}
@AfterReturning("myPointCut()")
public void MyAfterCut(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String methodName = method.getName();//获取执行方法名
System.out.println("==============MyAfterCut方法,执行完接口【"+methodName+"】之后触发=============");
}
}
再写一个接口
import io.renren.common.annotation.MyAnnotation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/anno")
public class MyAnnotationTest {
@GetMapping("test")
@MyAnnotation(name = "iFound")
public void test(String s1,String s2){
System.out.println("=============调用了接口方法============");
}
}
通过postman或者在浏览器中调试接口
http://localhost:端口号/项目名/anno/test?s1=1&s2=333
===========获取注解参数值==========
age= 23
name= iFound
===========获取注解参数值==========
方法传递的参数: 1
方法传递的参数: 333
==============MyBeforCut方法,执行接口【test】之前触发=============
=============调用了接口方法============
==============MyAfterCut方法,执行完接口【test】之后触发=============