【问题标题】:Using a CDI producer causes ambiguous dependencies exception使用 CDI 生产者会导致不明确的依赖异常
【发布时间】:2015-04-04 13:48:45
【问题描述】:

我需要将ApplicationScoped bean 的同一实例注入我的应用程序的多个位置,并创建了以下工厂类,它使用@PostConstruct 注释来初始化bean,并使用@Produces 注释返回bean 的同一个实例。

@ApplicationScoped
public class CommandBusFactory implements Serializable {

    private static final long serialVersionUID = 1L;

    private CommandBus commandBus;

    @PostConstruct
    public void init() {
        commandBus = new BasicCommandBus();
        // Do some stuff to configure the command bus
    }

    @Produces
    public CommandBus produceCommandBus() {
        return commandBus;
    }

}

我遇到的问题是当我部署应用程序 GlassFish 时返回以下错误消息:

Exception while loading the app : CDI deployment failure:WELD-001409 Ambiguous dependencies for type [CommandBus] with qualifiers [@Default] at injection point [[BackedAnnotatedField] @Inject private myapp.web.ToDoItemCommandController.commandBus]. Possible dependencies [[Producer Method [CommandBus] with qualifiers [@Any @Default] declared as [[BackedAnnotatedMethod] @Produces public myapp.core.cdi.CommandBusFactory.produceCommandBus()], Managed Bean [class myapp.core.commandhandling.BasicCommandBus] with qualifiers [@Any @Default]]]

我可以通过将 @Alternative 注释添加到 BasicCommandBus 类来克服此异常,但这似乎不是解决问题的最佳方法。

我不想在将CommandBus 注入我的应用程序的任何地方都添加限定符,因为使用CommandBus 的不同实现需要在多个位置更改代码。其目的是工厂的更高版本将读取配置文件,并根据配置文件中的值创建不同类型的CommandBus

我已经阅读了这个问题的答案 (https://stackoverflow.com/a/18782027/1274662) 并理解为什么会抛出不明确的依赖项异常,但我不知道是处理以下事实的最佳方法:有两个可能的 bean 可能考虑到我想决定使用哪个实现以及如何在中心位置初始化它,所以被注入。

我的问题是:

  1. BasicCommandBus 类上使用@Alternative 注释是正确的方法吗?

  2. 我应该使用更好的方法将ApplicationScoped bean 的相同实例(即CommandBus)注入我的应用程序的多个位置,同时控制创建的实现(即BasicCommandBusEnhancedCommandBus) 以及它是如何在中心位置初始化的?

【问题讨论】:

  • 您确定您的 CommandBusFactory 不会在您部署的应用程序中多次出现吗?在 EAR/lib 目录和 WAR/WEB-INF/lib 目录中都说?

标签: java jakarta-ee dependency-injection cdi


【解决方案1】:

如果你希望你的 bean 只能由生产者注入,你可以用 @Vetoed 注释 BasicCommandBusEnhancedCommandBus 这样你就不会在 bean 它本身和生产者方法之间产生歧义注入点是将注入实例的生产者。

【讨论】:

    猜你喜欢
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多