Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 377
Honza Zidek Avatar asked May 23 '26 06:05

Honza Zidek


1 Answers

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 e.g. 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.

like image 133
stg Avatar answered May 25 '26 19:05

stg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!