按名称在Micronaut中获取Bean

huangapple go评论121阅读模式
英文:

Get bean by name in Micronaut

问题

我有一个类似如下的接口

    interface Task {
      void run(String param);
    }

我有很多用 @Named("same_name") 注解标记的实现

我想要实现类似于 Spring 的获取方式

    @Inject
    ApplicationContext appContext    

    void execTask(String name, String param) {
      Task task = appContext.getBeam(Task.class, name);
      task.run(param);
    }

我成功地通过在bean定义中搜索注解来实现了这一点类似于

Groovy代码

    void execTask(String name, String param) {
      Collection<BeanDefinition<Task>> definitions = appContext.getBeanDefinitions(Task);
      BeanDefinition<Task> definition = definitions.find { BeanDefinition<Task> it ->
        it.getAnnotation(Named)?.stringValue()?.filter { it == name }?.present;
      }
      Task task = appContext.getBean(Task, definition.declaredQualifier);
      task.run(param);
    }

但这似乎对于一个简单的操作来说有点繁琐

有没有更直接的方式呢
英文:

I have an interface that looks like.

interface Task {
  void run(String param);
}

And I have many implementations annotated with @Named("same_name")

I want to get an implementation similar to Spring:

@Inject
ApplicationContext appContext    

void execTask(String name, String param) {
  Task task = appContext.getBeam(Task.class, name);
  task.run(param);
}

I managed to do this using a search for annotation in bean definitions, similar to:

(code in Groovy)

void execTask(String name, String param) {
  Collection&lt;BeanDefinition&lt;Task&gt;&gt; definitions = appContext.getBeanDefinitions(Task)
  BeanDefinition&lt;Task&gt; definition = definitions.find { BeanDefinition&lt;Task&gt; it -&gt;
    it.getAnnotation(Named)?.stringValue()?.filter {it == name }?.present
  }
  Task task = appContext.getBean(Task, definition.declaredQualifier)
  task.run(param)
}

but it seems like a lot for something simple.

is there a more direct way?

答案1

得分: 6

你可以通过名称限定符检索一个bean:

import io.micronaut.inject.qualifiers.Qualifiers

// ...

void execTask(String name, String param) {
    Task task = appContext.getBean(Task.class,
                                   Qualifiers.byName(name));
    task.run(param);
}
英文:

You can retrieve a bean with a name qualifier:

import io.micronaut.inject.qualifiers.Qualifiers

// ...

void execTask(String name, String param) {
    Task task = appContext.getBean(Task.class,
                                   Qualifiers.byName(name));
    task.run(param);
}

huangapple
  • 本文由 发表于 2020年10月27日 19:37:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64553631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定