问题描述
我收到以下 Micronaut 代码的 NonUniqueBeanException: Multiple possible bean candidates found:
:
@Context
@Slf4j
@AllArgsConstructor
public class RemoteService {
private final Provider<Session> remoteSessionFactory;
}
我有 2 个 Provider 的实现
@Slf4j
@Prototype
@AllArgsConstructor
public class RemoteSessionFactoryA implements Provider<Session> {
//some code here
}
@Slf4j
@Prototype
@AllArgsConstructor
public class RemoteSessionFactoryB implements Provider<Session> {
//some code here
}
我什至尝试过这样但仍然得到同样的错误:
private final @Named("remoteSessionFactoryA) Provider<Session> remoteSessionFactory;
请建议如何解决此问题。
问候
解决方法
advisory_agreement__advisory,value_1_29,3rd_party_key
注释应该是构造函数参数的一部分。由于让 Lombok 生成构造函数,因此无法通过 Lombok 设置 Named
注释。
我建议自己编写构造函数,例如:
@Named
Micronaut 无法注入 bean,因为名称与命名约定不匹配。 Micronaut 文档指出:
Micronaut 能够在前面的示例中注入 V8Engine,因为: @Named 限定符值 (v8) + 类型被注入的简单名称 (Engine) == (case-insensitive) == Engine (V8Engine) 类型的 bean 的简单名称 您也可以在 bean 的类级别声明 @Named 来显式定义 bean 的名称。
因此,如果您将名称放在源 bean 上,Micronaut 将选择您定义的名称。
@Context
@Slf4j
public class RemoteService {
private final Provider<Session> remoteSessionFactory;
public RemoteService(@Named("remoteSessionFactoryA") Provider<Session> remoteSessionFactory) {
this.remoteSessionFactory = remoteSessionFactory;
}
}
@Slf4j
@Prototype
@AllArgsConstructor
@Named("remoteSessionFactoryA")
public class RemoteSessionFactoryA implements Provider<Session> {
//some code here
}
@Slf4j
@Prototype
@AllArgsConstructor
@Named("remoteSessionFactoryB")
public class RemoteSessionFactoryB implements Provider<Session> {
//some code here
}
然后像这样注入
@Qualifier
@Retention(RUNTIME)
public @interface FactoryA {
}
@Qualifier
@Retention(RUNTIME)
public @interface FactoryB {
}