How to use Injection in user-made classes?


I have functionality common to multiple screen controllers, so I decided to make a new package in the web module, i.e., and a new class in this package.

I would like to Inject some of my Middleware Services, and ExportDisplay in MyClass, but injected elements are null. Is the only way of doing this to register MyClass as JavaBean and making it a singleton?

Or is it possible to inject in my plain class?

Thank you for your help!

Hi, this works.

You have to annotate it wizh @Component. Here’s an example where I did it as well:

Then you can use this class with the default dependency injection @Inject.


Hi Mario, thank you for your kind reply and reference project, it is very helpful.

MyClass had a constructor and private fields, which seem to prevent initializing the application when I add the @Component annotation.

Error initializing application
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘mailMergeGenerator’ defined in URL

For the time being, I gave up using injection and used AppBeans.get(ExportDisplay.class) instead, which solves my problem.

I would however like to understand why Injection works in my screen controllers but not in MyClass.

You can use injection for any class, even if it’s not a spring bean. E.g. we use injections for test classes.
You have to:

  1. Copy class com.haulmont.cuba.gui.ControllerDependencyInjector to your own MyDependencyInjector and remove all GUI-related stuff from the code.

  2. For every instance of your class you have to instantiate MyDependencyInjector and call myDependencyInjector.inject()
    You will have to do it manually right after your object’s instantiation, or invent how to automate it.

E.g. for test classes there are lifecycle rules and annotations.

Hi Alex,

Thank you for your explanation.
Best regards