Search code examples
javadependency-injectioncdi

Java EE CDI - obtaining a new instance of a class each time a method is called


I am looking to do some refactoring of a Java J2EE application, but I am not clear how to have CDI provide the needed dependencies:

The current setup is quite simple/easy to understand:

@ApplicationScoped
public class MyApplication  {


    @Inject
    @Named("Default")
    private Dependency dependency;

    public void dostuff(){
        dependency.process();
    }

}

I now need a new instance of dependency each time I call dostuff.

I am unclear on how to use CDI to create this for me. My Dependency has its own dependencies that I would like CDI to create for me.

I expect there is a layer of indirection I need to add.

Additional context: This class is part of a process that polls for work to be done, and is hosted in Wildfly. We are not using Spring in the project.


Solution

  • Since what you desire is having a new instance of Dependency, each time the method is called, I think what you need is an instance of Provider that is (javax.inject.Provider<T>) injected in your class/bean.

    Inject the provider to your current class:

    @Inject Provider<DesiredBean> provider;
    

    Then, in your method doStuff() obtain the new instance:

    DesiredBean desiredBean = provider.get();
    

    This should get you going.