SpringBoot自定义注解及AOP的开发和使用详解
一、引入 AOP 依赖
自定义注解一般会和 AOP(切面)
结合使用,所以我们首先需要在项目中引入相应的依赖。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
二、创建自定义注解 Log
annotation.Log:
import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Log { String value() default ""; }
@Target:
表明该注解可以作用的目标是谁,也就是你的注解是用来修饰方法?类?还是属性?这里是表明作用在方法上。@Retention:
表明该注解作用的生命周期,这里表明在运行时有效。@Documented:
表明被它修饰的注解将被javadoc
提取成文档。
三、创建 AOP切面类
aspect.LogAspect:
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; @Aspect @Component public class LogAspect { @Pointcut("@annotation(com.jk.annotation.Log)") public void pointCut(){} @Before("pointCut()") public void before() { System.out.println("前置通知..."); } @After("pointCut()") public void after() { System.out.println("后置通知..."); } @Around("pointCut()") public void around(ProceedingJoinPoint point) throws Throwable { System.out.println("环绕通知前..."); point.proceed(); System.out.println("环绕通知后..."); } }
@Aspect:
表明该类为切面类,定义切面类时必须加这个注解。@Component:
表明把该类交给IOC
容器控制。@Pointcut:
定义切入点,结合@annotation(@interface)
使用,表明该方法为切入点。@interface
必须写自定义注解的全路径名。@Before:
表明被自定义注解代理的方法执行前,先调用的方法。@After:
表明被自定义注解代理的方法执行后,return
前调用的方法。@Around:
将被自定义注解代理的方法封装起来,环绕通知(即在他之前之后通知),point.proceed()
表明执行的目标方法。
四、自定义注解测试
controller.TestController:
import com.jk.annotation.Log; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/test") public class TestController { @GetMapping @Log public void test() { System.out.println("执行test方法"); } }
在 test()
方法上添加了一个 @Log
注解,他会在执行这个方法时,执行我们之前定义切面时创建的前置方法、后置方法、环绕方法。
在 SpringBoot 中使用自定义注解就是如此简单,一般在通知方法中我们还会结合反射来获取执行方法的一些信息,如方法名,参数,响应值等,在后面我也会新开一篇文章专门讲讲反射,有兴趣的掘友可以关注一下哦!
到此这篇关于SpringBoot自定义注解及AOP的开发和使用详解的文章就介绍到这了,更多相关SpringBoot注解及AOP开发和使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot中@ConfigurationProperties实现配置自动绑定的方法
本文主要介绍了SpringBoot中@ConfigurationProperties实现配置自动绑定的方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-02-02MyBatis使用<foreach>标签like查询报错解决问题
这篇文章主要介绍了MyBatis使用<foreach>标签like查询报错解决问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-03-03
最新评论