dependency-injection - 如何解决 NonUniqueBeanException : Multiple possible bean candidates found in micron

标签 dependency-injection javabeans micronaut

对于以下 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/

相关文章:

spring - 如何在 Activiti JavaDelegate 中访问 spring bean?

java - 注入(inject)的父类(super class) Bean 如何注入(inject)错误的实例(子类 Bean 实例)?

java - 访问数据库并写入 Bean |最佳实践

gradle - 当我的应用程序依赖于依赖于不同micronaut版本的lib时,找不到匹配的micronaut-bom变体

java - 如何在测试方法中使用@Autowired

c# - 在使用 IoC 的 c#.Net 中,不使用构造函数直接将依赖项传递给方法是否可以?

java - 你是直接通过http传递hibernate/jpa实体对象还是有更好的选择?

java - 错误 : invalid source release 14 with --enable-preview

c# - 在使用 app.UseRewriter().Add() 添加重定向时访问 Startup.Configure 中的 dbcontext

带有 RoboGuice 2.0 的 Android 应用程序 - 如何使用应用程序上下文注入(inject)单例