英文:
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<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)
}
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论