阅读(3567) (0)

Micronaut Method Adapter Advice

2023-02-23 11:10:26 更新

在某些情况下,您希望根据方法上是否存在注释来引入新的 bean。这方面的一个示例是 @EventListener 注释,它为调用注释方法的每个注释方法生成 ApplicationEventListener 的实现。

例如,以下代码片段在 ApplicationContext 启动时运行方法中包含的逻辑:

import io.micronaut.context.event.StartupEvent;
import io.micronaut.runtime.event.annotation.EventListener;
...

@EventListener
void onStartup(StartupEvent event) {
    // startup logic here
}

@EventListener 注解的存在导致 Micronaut 创建一个新类来实现 ApplicationEventListener 并调用上面 bean 中定义的 onStartup 方法。

@EventListener 的实际实现很简单;它只是使用@Adapter 注释来指定它适应的 SAM(单一抽象方法)类型:

import io.micronaut.aop.Adapter;
import io.micronaut.context.event.ApplicationEventListener;
import io.micronaut.core.annotation.Indexed;

import java.lang.annotation.*;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
@Retention(RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@Adapter(ApplicationEventListener.class) (1)
@Indexed(ApplicationEventListener.class)
@Inherited
public @interface EventListener {
}
  1. @Adapter 注释指示要适应的 SAM 类型,在本例中为 ApplicationEventListener。

如果指定了 SAM 接口,Micronaut 还会自动对齐泛型类型。

使用此机制,您可以定义自定义注释,这些注释使用 @Adapter 注释和 SAM 接口在编译时自动为您实现 bean。