Java 自定义注解
一、Java 自定义注解的用途、
1、可以记录在特殊方法进行日志记录
2、可以进行 特殊鉴权 如 @ValidateRole(“admin") 只有当前用户拥有指定角色时才放行 否则抛自定义异常 无权限
3、可以用于参数 如 Controller 方法中的参数进行 参数格式验证
二、自定义注解记录需要重试的请求数据到数据库
2.1 pom 节点引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
启动需要加 @EnableAspectJAutoProxy
@SpringBootApplication @EnableAspectJAutoProxy @ComponentScan("com.lyb.*") public class OpenDemoApplication { public static void main(String[] args) { SpringApplication.run(OpenDemoApplication.class, args); } }
2.2 自定义注解名称
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RecordRetryMessage { /** * 保存重试消息类型 * @return */ int messageType() default 1; }
2.3 依赖切面 aspect 实现 自定义注解
@Aspect @Component public class RetryMessageAspect { @Autowired UserInfoService userInfoService; @Pointcut("@annotation(com.lyb.web.annotation.RecordRetryMessage)") public void retryMessage() { } @Around("retryMessage()") public Objectaround(ProceedingJoinPoint joinPoint) throws Throwable { Object[] objects = joinPoint.getArgs(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); RecordRetryMessage myLog = signature.getMethod().getAnnotation(RecordRetryMessage.class); System.out.println("注解上的参数值:" + myLog.messageType()); System.out.println("userInfoService.testC() = " + userInfoService.testC()); objects[1] = "修改后的参数值";
// 如果需要返回值需要
return joinPoint.proceed(objects);
}
}
2.4 使用自定义注解
@RecordRetryMessage(messageType = 1) public void testB(String l,String l1) { System.out.println("testB(); = "); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构