对于以下 Micronaut 代码,我收到 NonUniqueBeanException: Multiple possible bean Candidates:
:
@Context
@Slf4j
@AllArgsConstructor
public class RemoteService {
private final Provider<Session> remoteSessionFactory;
}
我有 2 个提供程序的实现
@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;
请建议如何解决此问题。
问候
最佳答案
Named
注释应该是构造函数参数的一部分。由于让 Lombok 生成构造函数,因此 Lombok 无法设置 @Named
注释。
我建议自己编写构造函数,例如:
@Context
@Slf4j
public class RemoteService {
private final Provider<Session> remoteSessionFactory;
public RemoteService(@Named("remoteSessionFactoryA") Provider<Session> remoteSessionFactory) {
this.remoteSessionFactory = remoteSessionFactory;
}
}
Micronaut 无法注入(inject) bean,因为名称与命名约定不匹配。 Micronaut 文档指出:
Micronaut is capable of injecting V8Engine in the previous example, because: @Named qualifier value (v8) + type being injected simple name (Engine) == (case-insensitive) == The simple name of a bean of type Engine (V8Engine) You can also declare @Named at the class level of a bean to explicitly define the name of the bean.
因此,如果您将名称放在源 beans 上,Micronaut 将选取您定义的名称。
@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 {
}
然后像这样注入(inject)
@Context
@Slf4j
public class RemoteService {
private final Provider<Session> remoteSessionFactory;
public RemoteService(@FactoryA Provider<Session> remoteSessionFactory) {
this.remoteSessionFactory = remoteSessionFactory;
}
}
关于dependency-injection - 如何解决 NonUniqueBeanException : Multiple possible bean candidates found in micron,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68112325/