Search code examples
javajakarta-eecdi

CDI best way for passing services


I have several service like that:

@Singleton
public SimpleService {
    ...
}

I have Managed Bean @ViewScoped which should create some complex objects. These objects should execute business-logic. I need to pass these services to this object.

Example of Managed Bean:

@ManagedBean
@ViewScoped
public class ExampleBean {
    @Inject
    private SimpleService simpleService;

    ...
    public void customLogic() {
        // in this method I should create complex object which should have services and some data.
        // current implementation
        ComplexObject object = new ComplexObject(SimpleService simpleService, ...)
    }
}

Services are injected to Managed Bean by @Inject annotation. For creating these objects - I'm using the constructor and pass these services as params. The question is: can I have better solution than passing services in constructor?


Solution

  • What you are doing is perfectly fine. You are using the ManagedBean as a bridge to inject the services and then passing the injected variables to a ComplexObject that need the services.

    The only restriction that should be considered is, could the ComplexObject class be a ManagedBean itself? That way you could inject everything directly on it, but if it is not possible, you may use the bean for that.

    I prefer the inject by field option mentioned because I think it is a little more readable.