Spring Boot中 自定义注解

Spring Boot中 自定义注解

  1. 定义一个注解

创建一个Java注解,可以使用@interface关键字来定义,例如:

less
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default "";
}

这个注解称为MyAnnotation,并且它具有一个value()属性。

  1. 使用注解

使用MyAnnotation注解,例如:

typescript
@MyAnnotation("This is a custom annotation")
public void myMethod() {
    // method implementation
}

在上面的例子中,我们使用@MyAnnotation注解来注释myMethod()方法,并为value()属性提供了一个字符串值。

  1. 处理注解

使用Spring Boot来处理自定义注解,可以通过以下步骤:

  • 创建一个注解处理器,例如:
java
@Component
public class MyAnnotationProcessor {

    @Autowired
    private MyService myService;

    @Around("@annotation(MyAnnotation)")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        // 方法执行前的逻辑
        String annotationValue = ((MethodSignature) joinPoint.getSignature())
                .getMethod().getAnnotation(MyAnnotation.class).value();
        // 调用原始方法
        Object result = joinPoint.proceed();
        // 方法执行后的逻辑
        myService.save(annotationValue);
        return result;
    }
}

在上面的例子中,我们创建了一个名为MyAnnotationProcessor的注解处理器,并使用Spring的@Component注解将其声明为一个Spring组件。该处理器中的process()方法将在使用@MyAnnotation注解注释的方法执行前后被调用。

  • 注册注解处理器

将注解处理器注册到Spring Boot应用程序上下文中,例如:

less
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

    @Bean
    public MyAnnotationProcessor myAnnotationProcessor() {
        return new MyAnnotationProcessor();
    }
}

在上面的例子中,我们创建了一个名为AppConfig的配置类,并使用Spring的@Configuration注解将其声明为一个Spring配置类。使用@EnableAspectJAutoProxy注解启用AspectJ自动代理,并使用@Bean注解创建了一个MyAnnotationProcessor实例,将其注册到Spring应用程序上下文中。

这样,当使用@MyAnnotation注解注释的方法被调用时,Spring将自动调用MyAnnotationProcessor处理器中的process()方法。

posted @ 2023-04-21 17:19  securitybob  阅读(341)  评论(0编辑  收藏  举报