'Dependency injection from Quarkus (java)
Colleagues, hello! Is is possible to inject beans inside of class which is created via 'new' operator? For example:
public class TestClass implements Callback {
@Inject
TestClassRepository repository;
//just only methods...
}
And 'TestClass' is created from another class:
Flyway.configure().collbacks(new TestClass()).load();
I have an issue with this,because 'repository.anyMethods()' inside of TestClass creates 'NullPointer' exception. 'TestClassRepository' is marked with the '@ApplicationScoped' and '@Startup' annotations.
Solution 1:[1]
@Singleton
public class TestConfig {
@javax.enterprise.inject.Produces
public TestClass testClass() {
return new TestClass();
}
}
another class annotated with the @ApplicationsScoped
or @Singleton
:
@Inject
public void method(TestClass testClass) {
Flyway.configure().collbacks(testClass).load();
// your code
}
If you create an object by yourself calling a constructor (new TestClass()
) then quarkus doesn't manipulate that object, and doesn't inject a repository.
Solution 2:[2]
No you cannot inject beans inside a class that is instanciate with the new keyword. But you can still find a way around like so :
@Dependent
public class BeanFactory {
@Inject
TestClassRepository repository
@Produces
public TestClass createTestClass() {
return new TestClass(this.repository);
}
You can find more details here : Quarkus Contexts and dependency Injection
Also you can define multiple beans for different profiles as mentionned few lines bellow Here
This means you can create a repository for your tests and one for prod or whatever is best for your case.
Also I do not think the annotation "@Startup" would add anything to your TestClassRepository bean.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | donquih0te |
Solution 2 | cigien |