MDP
MDP

Reputation: 4267

How to inject dependencies when doing Object object = new Object()

Is there a way to inject all the dependencies and sub-depencencies when I instantiate an object with the classic code Object object = new Object()?

As you can see from the code below, the class A autowires the class B, the class B autowires the class C.

When I instantiate the class A this way A a = new A(); of course the class A doens't have its dependencies B, and B doens't have its and so on.

Following this example I'm able to load the dependencies of A (so B is loaded inside A), but not the relative dependencies of B.

Is there a way to do it?

Thank you

public class Start{
    public void start(){
       A a = new A();
    }
}

public class A{
    @Autowired B b;
}

public class B{
   @Autowired C c;
}

public class C{   
}

Upvotes: 0

Views: 1205

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

Is the spring engine that creates an object and put the created instance in a field annotated with @Autowired.

If an object is not under the control of the spring engine no @Autowired field is instantied.

So you can't have a field correctly initialized if you create the container object explicitly with a new (so if it is not under the control of spring engine).

Upvotes: 1

Related Questions