java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java SpringBoot自定义注解

Java SpringBoot自定义注解的使用及说明

作者:Java皇帝

本文介绍了在Spring Boot中创建和使用自定义注解的方法,通过自定义注解,可以减少重复代码、增强代码可读性和可维护性,具体步骤包括定义注解、创建注解处理器以及在业务方法上使用注解

一、自定义注解的场景与优势

1.1 场景

在开发过程中,我们常常需要在多个地方实现相同的功能,例如日志记录、性能监控、权限验证等。

如果直接在每个业务方法中编写这些功能的代码,会导致代码重复和难以维护。

1.2 优势

使用自定义注解的优势在于:

二、创建自定义注解

2.1 定义注解

使用 @interface 关键字定义注解,并通过 @Retention@Target 等元注解来指定注解的保留策略和适用目标。

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD) // 指定注解适用的目标类型为方法
@Retention(RetentionPolicy.RUNTIME) // 指定注解的保留策略为运行时
@Documented
public @interface LogAnnotation {
    String module() default ""; // 模块名称
    String operation() default ""; // 操作描述
}

2.2 创建注解处理器

通过创建注解处理器(Aspect),利用 AOP(面向切面编程)来拦截带有自定义注解的方法,并在方法执行前后添加自定义逻辑。

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1) // 指定切面的顺序
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(LogAnnotation)") // 定义切点,匹配使用了 LogAnnotation 的方法
    public void logPointcut() {}

    @Before("logPointcut()")
    public void doBefore() {
        logger.info("方法执行前,添加日志记录逻辑");
    }
}

三、使用自定义注解

3.1 在业务方法上使用注解

在需要记录日志的业务方法上添加自定义注解,指定模块名称和操作描述。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class DemoController {
    @GetMapping("/test")
    @LogAnnotation(module = "测试模块", operation = "测试方法执行")
    public String test() {
        return "Hello, World!";
    }
}

3.2 配置类加载注解

确保 Spring 能够扫描到自定义注解和注解处理器,可以在主应用类或配置类上添加 @ComponentScan 注解,指定扫描的包路径。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "your.package.name") // 指定扫描的包路径
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

四、总结

在 Spring Boot 中创建和使用自定义注解,可以帮助我们实现代码的复用、增强代码的可读性和可维护性。

通过定义注解、创建注解处理器,并在业务方法上使用注解,可以轻松实现诸如日志记录、性能监控、权限验证等功能。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文