【问题标题】:Declare @Inject as concrete implementation of @Produces returned interface将@Inject 声明为@Produces 返回接口的具体实现
【发布时间】:2016-09-11 07:57:05
【问题描述】:

有没有办法注入@Produces返回接口的具体实现?

SomeClassImpl implements SomeClass {
    public Integer iField;
}

生产者类:

@Produces
public SomeClass produceChild(){
    SomeClassImpl impl = new SomeClassImpl();
    impl.iField = 17;
    return impl;
}

消费类:

@Inject SomeClassImpl classImpl;

编辑

尝试@Inject SomeClassImpl 不会强制容器使用返回超类型SomeClass@Produces 方法。

为什么可以通过@Injectparent-type(没有Producer)注入child-type,但是没有变种通过@Producesparent-type注入child-type?

【问题讨论】:

  • 如果您有多个接口实现,请使用qualifiers
  • this answer
  • 关于您的编辑,因为您的 @Produces 方法会生成 SomeClass 实例,而不是 SomeClassImpl 实例,它可以返回 SomeClass 的任何实现,而不仅仅是 SomeClassImpl 实例.您可以通过注入 SomeClass(不是实现)并使用限定符来修复它,或者修改您的 @Produces 方法以返回 SomeClassImpl
  • 我明白了,谢谢,但我需要通过 Produces 方法准确地注入 SomeClassImpl 类型。如果不可能 - 请告诉我“这不可能!” =))

标签: jakarta-ee interface cdi implementation producer


【解决方案1】:

您可以使用@Typed 来控制您的bean 的有效类型。 https://docs.jboss.org/cdi/api/1.0/javax/enterprise/inject/Typed.html

【讨论】:

    猜你喜欢
    • 2013-11-13
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2011-02-15
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多