I have a Spring component in which I inject dependencies (other components), but I am unable to use these injected dependencies in the constructor as they are null
at the time of constructor call. Is there a way to use these dependencies in the constructor?
@Component
@RequestScope
public class MyComponent {
@Inject
OtherComponent1 otherComponent1
@Inject
OtherComponent2 otherComponent2
MyComponent() {
otherComponent1.someMethod(); // null
otherComponent2.someMethod(); // null
}
}
There are two injection methods in Spring: property injection (as you used) and constructor injection. For property injection, the Spring bean factory will create your bean using its default constructor (MyComponent
)(And that's why you need default constructors for @Component
annotated classes) first, and then the Spring framework will inject OtherComponent1
and OtherComponent2
after they are fully constructed (with all their dependencies injected). Therefore, when MyComponent()
is called, the properties otherComponent1
and otherComponent2
are just normal properties initialized to null
. To use these dependencies, you should use constructor injection.
Code as follows:
@Component
@RequestScope
public class MyComponent {
OtherComponent1 otherComponent1
OtherComponent2 otherComponent2
MyComponent(OtherComponent1 otherComponent1, OtherComponent2 otherComponent2) {
this.otherComponent1 = otherComponent1;
this.otherComponent2 = otherComponent2;
this.otherComponent1.someMethod(); // call methods ok
this.otherComponent2.someMethod(); // call methods ok
}
}