简体   繁体   中英

Define bean using factory method in plain Java EE - WITHOUT Spring

I want to create a bean which can be automatically injected (autowired) by plain Java EE, not with Spring .

The code I have is this:

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

@ApplicationScoped
public class MyConnector {
    ....
    private Client client = ClientBuilder.newClient();
    ....
}

I'd like to use dependency injection like that instead:

    @Inject
    private Client client;

In good old Spring I would just define the bean following the guideline http://docs.spring.io/spring/docs/3.1.0.M1/spring-framework-reference/html/beans.html#beans-factory-class-static-factory-method

<bean id="client"
    class="javax.ws.rs.client.ClientBuilder"
    factory-method="createInstance"/>

and the @Autowired would inject the proper bean.

QUESTION : Can I achieve the same somehow in the plain Java EE without Spring? Can I define a bean in a similar way - and if so, where (in which configuration file)?

You may write your own CDI producer for this purpose

@Dependent public ClientFactory{
   @Produces Client createClient() {
       return ClientBuilder.newClient(); 
   }
}

Now you are able to use CDI's @Inject to get an instance within your Bean

@ApplicationScoped public class MyConnector {    
    @Inject private Client client;
}

With those kind of producers, CDI provides an easy-to-use implementation of the factory pattern. You are able to inject nearly everything and everywhere, not only Classes but also Interfaces, other JEE ressources and even primitive types. The injection point do not have to be a class member, but may also be eg an argument in a method ...

Each injection will give you a different Proxy, so you are able to inject even more than one Client to your Bean if you have to. If those Proxy objects refer to the same instances or not depends on your implementation of the factory method, but usually you do not want this.

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