如何解决 NonUniqueBeanException:在 micron 中发现多个可能的候选 bean

How to resolve NonUniqueBeanException: Multiple possible bean candidates found in micron

我得到 NonUniqueBeanException: Multiple possible bean candidates found: 以下 Micronaut 代码:

@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;

请建议如何解决这个问题。

此致

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 无法注入 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.

因此,如果您将名称放在源 bean 上,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 {
}

然后像这样注入

@Context
@Slf4j
public class RemoteService {
   private final Provider<Session> remoteSessionFactory;

   public RemoteService(@FactoryA Provider<Session> remoteSessionFactory) {
       this.remoteSessionFactory = remoteSessionFactory;
   }
}