简体   繁体   中英

How do I instantiate a CDI bean by passing an object as parameter just like I instantiate a new object in plain Java from a parameterized constructor?

In simple Java, we can construct an object by passing another object as an argument to its parameterized constructor. What would be the simply CDI way of doing that?

The CDI specification provides several mechanisms to instantiate beans. The closest mechanism from that of the Java constructor is called the bean constructor that the container calls to instantiates a bean class. That bean constructor may have any number of parameters, that are injection points and that get injected by the container as documented in injection using the bean constructor , eg:

public class FooBean {

    @Inject
    public FooBean(BarBean bar) {
    }
}

In addition to the bean constructor mechanism, the CDI specification provides other ways of instantiating / parameterizing bean instances, as documented in injection of fields and initializer methods , which are:

The Producer method mechanism can also be used as documented in invocation of producer or disposer methods .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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