Ced
Ced

Reputation: 17337

Release Cdi injected object from application scoped Bean

If I have an @ApplicationScoped bean that use injection only in the @PostConstruct method like so :

@Named
@ApplicationScoped
public class CountriesConverter implements Converter {
    private List<Country> countries;

    @Inject
    private CountriesService cs;

    @PostConstruct
    public void init() {
        this.countries = cs.getAllCountries();
    }
 ...
}

Does that mean that the bean needlessly holds onto an unnecessary dependency ? In the case of the injection of a service that request the DB, does that mean that there is one less service object in the pool ? Is it worth worrying about ? If so can I release the dependency ?

Upvotes: 2

Views: 518

Answers (1)

jvalli
jvalli

Reputation: 721

The runtime contents of the cs field depends on the scope of CountriesService. If it's in a normal scope (@ApplicationScoped, @RequestScoped, @SessionScoped etc), you'll have a proxy rather than the concrete object. If it was in a pseudoscope (@Dependent or no annotation at all, or a custom scope) then you end up with a concrete instance of the class.

If you have a proxy, every time you make a call to methods in the proxy the CDI container will retrieve the appropriate contextual instance and delegate the request to that object. If the scope did not contain an applicable object a new one will be created and placed into the context, then the request gets delegated to that object. The object gets cleaned up when the context is destroyed (end of request, end of http session etc).

To address the specific questions:

Does that mean that the bean needlessly holds onto an unnecessary dependency ?

If CountriesService is a dependent bean, yes. In that case you can set the field to null after you're done, or inject an Instance instead of the object itself.

@Inject
private Instance<CountriesService> serviceInstance;

@PostConstruct
private void init() {
    this.countries = serviceInstance.get().getAllCountries();
}

In the case of the injection of a service that request the DB, does that mean that there is one less service object in the pool ?

The concept of a pool doesn't apply to CDI beans. There is no pool in that sense, CDI doesn't care about concurrency at all. If you're using a stateless EJB then you have a proxy that points to the pool so you're still fine.

Is it worth worrying about ?

Most likely not. If CountriesService is a massive, dependent-scoped bean then maybe, but in that case there may be something wrong with your architecture :)

Upvotes: 3

Related Questions