Can anyone explain why @Inject
object are null when its class is initialized with new
operator?
public class A{
@Inject
B b;
...
...
}
When the above class is created as A a = new A();
I get b
as null
. Can anyone explain why? I know it works when I Inject class A. But I want to know why it doesn't work with new operator. What does spring do?
Frameworks that apply the Constrained Construction anti-pattern can make using Constructor Injection difficult. The main disadvantage to Constructor Injection is that if the class you're building is called by your current application framework, you might need to customize that framework to support it.
Both of these annotations use the 'AutowiredAnnotationBeanPostProcessor' to inject dependencies. '@Autowired' and '@Inject' can be used interchangeable to inject Spring beans.
Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC container will use the setter injection. Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like constructor.
The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
The dependancy injection is handled by spring container, so only objects which are created by the container will be subjected to it
In this case you are creating an object manually using new
operator, the spring container will not know about the object creation.
A possible solution is to use @Configurable
Annotation (and AspectJ) to solve this as given in the documentation
Also have a look at this answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With