一、自定义注解的场景与优势
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 中创建和使用自定义注解,可以帮助我们实现代码的复用、增强代码的可读性和可维护性。
通过定义注解、创建注解处理器,并在业务方法上使用注解,可以轻松实现诸如日志记录、性能监控、权限验证等功能。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论