0

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{   
}
MDP
  • 4,177
  • 21
  • 63
  • 119
  • 1
    No. The Java language does not allow you to "hook" into the object creation mechanism. (There's nothing like overloading `new` like in C++.) `new` will allocate an object and invoke the constructor, that's all. No dependency injection framework can do magic. – aioobe Jan 11 '16 at 13:54
  • 2
    Looks like an duplicate question: https://stackoverflow.com/questions/3813588/how-to-inject-dependencies-into-a-self-instantiated-object-in-spring – schrieveslaach Jan 11 '16 at 14:01

1 Answers1

1

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).

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56