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);
    }
}
相关推荐
廋到被风吹走2 小时前
【Spring】Spring Data JPA Repository 自动实现机制深度解析
java·后端·spring
MX_93592 小时前
Spring中Bean的配置(一)
java·后端·spring
sg_knight6 小时前
Spring 框架中的 SseEmitter 使用详解
java·spring boot·后端·spring·spring cloud·sse·sseemitter
郑州光合科技余经理8 小时前
同城系统海外版:一站式多语种O2O系统源码
java·开发语言·git·mysql·uni-app·go·phpstorm
一只乔哇噻8 小时前
java后端工程师+AI大模型开发进修ing(研一版‖day60)
java·开发语言·人工智能·学习·语言模型
Dolphin_Home8 小时前
笔记:SpringBoot静态类调用Bean的2种方案(小白友好版)
java·spring boot·笔记
MetaverseMan9 小时前
Java虚拟线程实战
java
浪潮IT馆9 小时前
Tomcat运行war包的问题分析与解决步骤
java·tomcat
悟能不能悟9 小时前
Caused by: java.sql.SQLException: ORA-28000: the account is locked怎么处理
java·开发语言
_院长大人_10 小时前
MyBatis Plus 分批查询优化实战:优雅地解决 IN 参数过多问题(实操)
java·mybatis