有没有一种很好的方法在其构造函数中创建具有一些参数的新Object,并且还要在其中注入CDI bean?

时间:2014-12-05 19:34:22

标签: java dependency-injection cdi

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()创建?

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

1 个答案:

答案 0 :(得分:2)

有一种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();