java在jdk1.5中引入了注解,spring框架也正好把java注解发挥得淋漓尽致。
接下来简单介绍如何在Spring中自定义注解,其中会使用到spring框架中的AOP(面向切面编程)。
一、创建自定义注解
首先创建自定义注解LogAnnotation,desc 为自定义的一个参数
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited()
public @interface LogAnnotation {
String desc();
}
二、解析注解
接着完成注解的解析工作,这里使用了spring的AOP(面向切面编程)特性
通过@Aspect注解使该类成为切面类
通过@Pointcut 指定切入点 ,这里指定的切入点为LogAnnotation注解类型,也就是被@LogAnnotation注解修饰的方法,进入该切入点。
- @Before 前置通知:在某连接点之前执行的通知,但这个通知不能阻止连接点之前的执行流程(除非它抛出一个异常)。
- @Around 环绕通知:可以实现方法执行前后操作,需要在方法内执行point.proceed(); 并返回结果。
- @AfterReturning 后置通知:在某连接点正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回。
- @AfterThrowing 异常通知:在方法抛出异常退出时执行的通知。
- @After 后置通知:在某连接点正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回。
package com.blue.module.annotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect //AOP 切面
@Component
public class CommonLogAspect {
/*通过@Pointcut指定切入点 ,这里指定的切入点为LogAnnotation注解类型,也就是
被@LogAnnotation注解修饰的方法,进入该切入点*/
@Pointcut(value = "@annotation(com.blue.module.annotation.LogAnnotation)")
private void pointcut() {
}
/**
* 在方法执行前后
*
* @param point
* @param logA
* @return
*/
@Around(value = "pointcut() && @annotation(logA)")
public Object around(ProceedingJoinPoint point, LogAnnotation logA) {
System.out.println("执行了around方法");
String msg = logA.desc();
//拦截的类名
Class clazz = point.getTarget().getClass();
//拦截的方法
Method method = ((MethodSignature) point.getSignature()).getMethod();
System.out.println("执行了类:" + clazz + " 方法:" + method + " 自定义消息:" + msg);
try {
return point.proceed(); //执行程序
} catch (Throwable throwable) {
throwable.printStackTrace();
return throwable.getMessage();
}
}
/**
* 方法执行后
*
* @param joinPoint
* @param logA
* @param result
* @return
*/
@AfterReturning(value = "pointcut() && @annotation(logA)", returning = "result")
public Object afterReturning(JoinPoint joinPoint, LogAnnotation logA, Object result) {
System.out.println("执行了afterReturning方法: result=" + result);
return result;
}
/**
* 方法执行后 并抛出异常
*
* @param joinPoint
* @param logAnnotation
* @param ex
*/
@AfterThrowing(value = "pointcut() && @annotation(logAnnotation)", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, LogAnnotation logAnnotation, Exception ex) {
System.out.println("执行了afterThrowing方法");
System.out.println("请求:" + logAnnotation.desc() + " 出现异常");
}
}
三、使用自定义注解
在controller中直接使用注解@LogAnnotation
@RestController
public class TestController{
@LogAnnotation(desc="My annotation")
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
启动项目,访问 http://localhost:8080/hello
结果
执行了around方法
执行了类:class com.blue.module.controller.TestController 方法:public java.lang.String com.blue.module.controller.TestController.hello() 自定义消息:My annotation
执行了afterReturning方法: result=hello
以上就是大概的Spring实现自定义注解的简单流程。