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{   
}
2
  • 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. Commented Jan 11, 2016 at 13:54
  • 2
    Looks like an duplicate question: stackoverflow.com/questions/3813588/… Commented Jan 11, 2016 at 14:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.