【问题标题】:Is there a nice way create new Object with some parameters in its constructor and also to have CDI beans injected in it?有没有一种很好的方法可以在其构造函数中创建带有一些参数的新对象,并在其中注入 CDI bean?
【发布时间】:2014-12-09 09:05:19
【问题描述】:
Example:

@Dependant 
public class SomeStartingPoint {

@Inject
private SomeService someService;

   public void doSomething(Long aLong, MyCustomObject myObject) {
       NotABean notABean = new NotABean(aLong, myObject);
       someService.doStuffWithNotABean(notABean);
   }
}


public class NotABean {

@Inject
private WouldBePerfectIfThisWouldBeManagedBean somehowInjectedBean;

   public NotABean(Long aLong, MyCustomObject myObject) {
      //set state
   }
}

所以问题是,有没有一种很好的方法可以将一些东西注入到 NotABean 对象中,它应该有状态,因此由 new() 创建?

当然,在当前情况下,我可以将 WillBePerfectIfThisWouldBeManagedBean 作为参数传递给构造函数,但这与问题无关。

【问题讨论】:

  • 也许您真的希望 CDI bean 成为可以结合注入参数和调用时参数的工厂。
  • 您使用的是 CDI 1.1 还是 1.0?
  • 1.0. 1.1有这个功能吗?
  • 在 1.1 中做起来要容易一些。我会将两者都包含在答案中。

标签: java dependency-injection cdi


【解决方案1】:

有一种 CDI 1.0 方式和一种 CDI 1.1 方式来执行此操作。 1.1 的方式比 1.0 容易得多,这就是他们创建它的原因。

这是来自 DeltaSpike 的示例:https://github.com/apache/deltaspike/blob/34b713b41cc1a237cb128ac24207b76a6bb81d0c/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java#L437

    CreationalContext<T> creationalContext = beanManager.createCreationalContext(null);

    AnnotatedType<T> annotatedType = beanManager.createAnnotatedType((Class<T>) instance.getClass());
    InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(annotatedType);
    injectionTarget.inject(instance, creationalContext);

假设您有某个对象的实例,该对象的字段或方法注释为 @Inject,它将满足这些依赖关系。

在 CDI 1.1 中,您可以做相反的事情。使用类Unmanaged,您可以实例化您的类的非托管实例。之后您需要调用 setter 来设置值。

   Unmanaged<Foo> fooU = new Unmanaged(Foo.class);
   Foo foo = fooU.newInstance().get();

不使用@Inject 的另一种方法是使用CDI 1.1 实用程序类手动获取引用。因此,您可以执行以下操作,而不是注入对 SomeService 的引用:

   SomeService someService = CDI.current().select(SomeService.class).get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多