首页 > 编程知识 正文

spring自定义注解切面,java注解

时间:2023-05-05 04:39:28 阅读:144281 作者:1904

创建springboot项目

下一步直接完成就行了。

引入aop依赖关系并在aop中实现自定义注释(不需要指定版本,spring-boot-starter软件包将自动与版本匹配) ) )。

ependencygroupidorg.spring framework.boot/groupidartifactidspring-boot-starter-AOP/artifact id/dependency注释类

创建完成后,在类中单击@,会看到您写的这个评论

package com.example.custom annotation.com mon; import java.lang.annotation.*; /** * @desc:自定义注释* @ author : liuchang * @ since :2021/8/31 * * @文档注释信息将添加到Java文档中* @target(elementtypppet ) () ) ) ) ) 652 @ retention (retention policy.XXX )需要保留多少注释(* @ inhenty ) @documented@target ) elementttype.method )是否可以继承) retention public @ interfacecustomanno (/element type.method其中

说明具体参数的含义。

@target(elementtype.type )//接口、类、枚举和注释

@target(elementtype.field ) /字段,枚举的常量

@target(elementtype.method )//方法

@target(elementtype.parameter ) /方法参数

@ target (element type.constructor ) /构造函数

@ target (element type.local _ variable ) /局部变量

@ target (element type.annotation _ type )//注释

类型为@target(elementtype.package )//软件包(retention ) retentionpolicy.source ) ——的Annotations仅在源代码级别保留

类型为@ retention (retention policy.class ) ——的Annotations在编译时被保留,存在于class文件中,但忽略JVM

@ retention (retention policy.runtime ) ——这种类型的Annotations保留给JVM,可以在运行时由JVM或使用反射的其他代码读取和使用。 对如何创建aop和定义触点并添加自定义注释执行一些操作。 操作主要包括

package com.example.custom annotation.com mon; importorg.AspectJ.lang.join point; importorg.AspectJ.lang.proceeding join point; importorg.AspectJ.lang.annotation.*; importorg.spring framework.stereotype.com ponent; /** * @desc:自定义注释的AOP * @ author : liuchang * @ since 33602021/8/31 * @ aspect是必需的! //@ aspect @ componentpublicclasscustomaspect (/@ pointcut需要定义接点位置(annotation ) XXX )获取自定义笔记本对象//声明一个接点和接点注释类的位置@ pointcut (@ annotation (com.example.custom annotation.com mon.custom anno ) ) )私有语音定制@Around () () * @Around ) ' customanno ) ) )公共语音识别(public void advice (proceedingjoinpointproceedingjoinpointprointproint ) ) ) ) ) ) ) //执行(必须声明)到此为止进入的方法体(system.out.println ) ' aroundend ' ); 如果要获取(/)注释中的属性,可以直接注入注释(/)方法来修改参数。 可以同时设定多个方法,在@Before接点执行之前设定@before(customanno ) ) (public void record (join point ) ) }//@After接点执行后}} @Before、预通知、方法前运行

@Around、环绕立体声扩展、目标方法执行前后执行的代码

@AfterReturning,处理请求并返回的内容

@AfterThrowing,目标方法抛出异常并执行

@After后置通知,在方法后运行自定义注释测试以创建控制器,并测试自定义注释是否有效。 必须添加web依赖项才能使用@RestController

ependencygroupidorg.spring framework.boot/groupidartifactidspring-boot-starter-web/artifact id/dependencypackagagagar importorg.spring framework.web.bind.annotation.request mapping; importorg.spring帧web.bind.annotation.rest controller;/* * * @测试desc :自定义注释是否有效* @ author : liuchang * @ since 33602021/8/31 */@ restcontrollerpubliclastestesttted test ' )公共语音获取日志) {system.out.} }然后使用postman进行访问测试

IDEA控制台打印结果:

Around BeginBefore调用自定义注释AfterAround End主要是围绕注释的方法执行附加操作。

微信公众号:关注FluencyHome (程序员族)同时更新,随时可以看文章。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。