Springboot (六) aop自定义注解开发
前言: 相信用过Spring的对Aop都不陌生,闲话不多说直接上列子。
1. 导入依赖
首先我们要导入aop的依赖,有了boot开发就是方便。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 编写例子
-
首先我们的需求是,需要一个日志注解,在方法上,可以截获关于方法的信息,并存到DB(数据库)中。@within 支持切入整个类方法
-
日志注解类
注解中有一个备注属性。
@Inherited @Documented @Target(ElementType.METHOD,ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface LogAnnotation { String value() default "默认备注"; }
-
编写我们的切面类
@Aspect @Component public class LogAspect { // 切入点 @Pointcut("@within(com.yu.annotationdemo.annotation.LogAnnotation)||@annotation(com.yu.annotationdemo.annotation.LogAnnotation)") public void logAnnotationPointcut() { } // 环绕通知 @Around("logAnnotationPointcut()") public Object myAnnotationAround(ProceedingJoinPoint joinPoint) throws Throwable { //获取目标类名 String targetName = joinPoint.getTarget().getClass().getName(); //获取方法名 String methodName = joinPoint.getSignature().getName(); //获取相关参数 Object[] arguments = joinPoint.getArgs(); //生成类对象 Class targetClass = Class.forName(targetName); //获取该类中的方法 Method method = targetClass.getMethod(methodName, String.class); Object proceed = joinPoint.proceed(); System.out.println("方法结束后"); LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class); if (logAnnotation != null) { String logAnnotationValue = logAnnotation.value(); // todo 将需要的日志信息 插入db中 } return proceed; } }
-
** 编写目标方法**
@RestController @RequestMapping("log") public class LogServiceImpl { @LogAnnotation("查询用户id") @RequestMapping("getUserId") public String getUserId(String id){ return id; } }
-
运行boot的启动类。访问目标URL查看结果。
我们简单的入门例子就结束了,很简单的代码。
附上其他的几钟通知类型: