4

I have a dependent class B of class A that I want injected into A.

And so I use the @Autowired annotation in class A. But class A itself I create using new keyword and I find that the reference to class B is null.

So if you are using Autowired, must Spring manage class A also?

I mean, is the null reference because I am using new and not letting Spring manage the whole thing?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Jeff
  • 1,513
  • 4
  • 18
  • 34
  • You are correct. Spring needs to bootstrap the entire application - if you use DI there should not be a single `new` anywhere. – Boris the Spider Dec 04 '15 at 13:05
  • Possible duplicate of [How to inject dependencies into a self-instantiated object in Spring?](http://stackoverflow.com/questions/3813588/how-to-inject-dependencies-into-a-self-instantiated-object-in-spring) – talex Dec 04 '15 at 13:09

2 Answers2

3

Yes, the both classes need to be in the same context. Manage by Spring.

You can see an example here. http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

reos
  • 8,766
  • 6
  • 28
  • 34
0

Yes, Spring container should manage objects of class A and B to be able to inject B reference into A.

pomkine
  • 1,605
  • 4
  • 18
  • 29