-1

Suppose I have annotated a class X with @Component and somewhere else in my application I initiate this class explicitly by new X().

Will this class still be managed by Spring? And if not, is there a way to autowire another class Y inside this X class (that is not managed)?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
user5157427
  • 241
  • 2
  • 7
  • 17
  • 1/ No. 2/ I don't see why not (but you might want to post some code) –  Jul 27 '15 at 20:10
  • If you describe the reason why and the environment in which you want to do that, someone might have a suggestion on how to achieve it using Spring. – hzpz Jul 27 '15 at 20:33
  • could be related: [Injecting dependencies using @Autowired into objects created with “new …”](http://stackoverflow.com/q/5418945/217324) – Nathan Hughes Jul 27 '15 at 20:38

1 Answers1

1

No and no. For Spring to manage an object, it must be created as a bean or annotated with @Component (or its derivatives), and instantiated by the container. You can only use @Autowired to inject dependencies into managed objects. This injection happens when the container is starting up, so any non-managed object will fail to have its dependencies injected.

woemler
  • 7,089
  • 7
  • 48
  • 67