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
  • 95,415
  • 23
  • 151
  • 231
Jeff
  • 1,383
  • 3
  • 17
  • 30
  • 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,090
  • 4
  • 26
  • 33
0

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

pomkine
  • 1,575
  • 4
  • 17
  • 29