简体   繁体   English

有没有什么好方法可以在其构造函数中创建带有某些参数的新Object并在其中注入CDI bean?

[英]Is there a nice way create new Object with some parameters in its constructor and also to have CDI beans injected in it?

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
   }
}

So the question is, is there a nice way to have something injected into the NotABean object, which supposed to have state in it, thus created by new()? 所以问题是,是否有一种很好的方法将某些东西注入到NotABean对象中,该对象应该具有状态,并因此由new()创建?

Of course, in current situtation I could pass WouldBePerfectIfThisWouldBeManagedBean as an argument to constructor, but this is not related to the question. 当然,在当前情况下,我可以将WouldBePerfectIfThisWouldBeManagedBean作为构造函数的参数传递,但这与问题无关。

There's a CDI 1.0 way and a CDI 1.1 way to do this. 有一种CDI 1.0和CDI 1.1方式可以做到这一点。 The 1.1 way is much easier than 1.0, hence why they created it. 1.1的方式比1.0容易得多,因此他们为什么要创建它。

Here's an example from DeltaSpike: https://github.com/apache/deltaspike/blob/34b713b41cc1a237cb128ac24207b76a6bb81d0c/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanProvider.java#L437 这是来自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);

Assuming you have an instance of some object that has fields or methods annotated @Inject it will satisfy those dependencies. 假设您有某个对象的实例,该对象的实例或方法带有@Inject批注,它将满足那些依赖关系。

In CDI 1.1, you can do the opposite. 在CDI 1.1中,您可以执行相反的操作。 Using the class Unmanaged you can instantiate unmanaged instances of your class. 使用Unmanaged类,您可以实例化类的Unmanaged托管实例。 You would need to call setters afterwards to set the values. 您随后需要调用设置器来设置值。

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

One other way, without using @Inject is to use the CDI 1.1 utility class to manually get references. 不使用@Inject另一种方法是使用CDI 1.1实用程序类手动获取引用。 So instead of injecting a reference to SomeService you could do: 因此,除了注入对SomeService的引用之外,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM