java中自定义注解

文章目录

自定义一个注解

java 复制代码
// 元注解:定义注解的行为
@Retention(RetentionPolicy.RUNTIME) // 注解在运行时保留,可通过反射读取
@Target(ElementType.METHOD)        // 注解只能用于方法上
public @interface LogExecution {
    String value() default "Method executed"; // 成员变量(带默认值)
}

注解要做的逻辑

如果你不是 spring web 项目,你可能需要手动实现注解的处理逻辑

如果你是 spring 的 web 项目,其中一半会引入 spring-boot-starter-aop 依赖,其中含有 aspect 相关注解使用,因此你可以使用 aop 代码来实现注解逻辑

java 复制代码
@Aspect
@Component
public class LoggingAspect {
    @Around("@annotation(logExecution)") // 匹配带有 @LogExecution 的方法
    public Object logExecutionTime(ProceedingJoinPoint joinPoint, LogExecution logExecution) throws Throwable {
        long start = System.currentTimeMillis();

        // 执行目标方法
        Object result = joinPoint.proceed();

        long duration = System.currentTimeMillis() - start;
        System.out.println("【日志】" + logExecution.value() + ",耗时: " + duration + "ms");
        return result;
    }
}
  • @Before:方法执行前。
  • @After:方法执行后。
  • @AfterReturning:方法成功返回后。
  • @AfterThrowing:方法抛出异常后。
  • @Around:环绕方法执行(可自定义逻辑)

使用自定义注解

java 复制代码
@Service
public class UserService {
    @LogExecution("创建用户")
    public User createUser(String name) {
        return new User(name);
    }
}
相关推荐
hqxstudying10 分钟前
Java向量化
java·开发语言
●VON1 小时前
重生之我在暑假学习微服务第七天《微服务之服务治理篇》
java·学习·微服务·云原生·nacos·架构·springcloud
你知道烟火吗1 小时前
谈谈对反射的理解?
java·开发语言·spring boot·后端
我爱996!1 小时前
Spring IoC&DI
java·后端·spring
啊阿狸不会拉杆1 小时前
《Java 程序设计》核心知识点梳理与深入探究
java·开发语言·python·算法·php·intellij-idea
盖世英雄酱581362 小时前
事务报错,为何数据还是插入成功了❓
java·数据库·后端
it自2 小时前
Redisson在Spring Boot项目中的集成与实战
java·spring boot·redis·后端·缓存
一勺-_-2 小时前
全栈:怎么把IDEA和Maven集成一下?
java·maven·intellij-idea
燕山石头2 小时前
解决 IntelliJ IDEA Build时 Lombok 不生效问题
java·前端·intellij-idea
Asu52022 小时前
链表反转中最常用的方法————三指针法
java·数据结构·学习·链表