Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject doesn't work with new operator

Tags:

java

spring

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?

like image 428
vicky Avatar asked Jun 18 '13 07:06

vicky


People also ask

Is it difficult to inject dependency by constructor?

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.

Can I use @inject in spring boot?

Both of these annotations use the 'AutowiredAnnotationBeanPostProcessor' to inject dependencies. '@Autowired' and '@Inject' can be used interchangeable to inject Spring beans.

Does constructor injection override setter injection?

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.

How do you inject dependencies?

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.


1 Answers

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

like image 140
Arun P Johny Avatar answered Nov 07 '22 13:11

Arun P Johny