3

I want to inject prototype beans into a singleton factory. we're considering 4 options, and would like someone to emphasize the differences.

Sorted according to my personal preference:

  1. use @lookup method annotation (we use code based configuration).
  2. @Autowired a Provider (one for each bean) and get() for each type.
  3. Provide static access to ApplicationContext.getBean() from anywhere in the application, and getBean() from there.
  4. inject ApplicationContext, and getBean().

I know getBean() is a bad practice, but for some reason, I see many answers directing this way.

(whats the big difference between options 2 & 3 ?)

Community
  • 1
  • 1
Nati
  • 1,034
  • 5
  • 19
  • 46
  • 2
    3 is something that could haunt you in a nightmare, but shouldn't make it to reality. 4 is close to that, but lamer. – Marko Topolnik Aug 05 '15 at 15:28
  • @MarkoTopolnik - it does feel wrong & dirty, but I need a real explanation why we have to destroy this piece of code. – Nati Aug 05 '15 at 15:31
  • My problem is where to start. Global variables are always bad because you completely lose control over their scope of usage; exposing the ApplicationContext as a global is particularly disgusting because it's the entrails of your entire application: now any piece of code, anywhere, can do to it what it wants. IoC stands for _inversion_ of control; with this you undo the inversion. For your app, the container is just a bag of things and you can take things in and out whenever you feel like it. – Marko Topolnik Aug 05 '15 at 15:34
  • @MarkoTopolnik but doesn't the javax Provider do the same ? – Nati Aug 05 '15 at 15:35
  • Do what the same? Make the complete IoC container publicly available? – Marko Topolnik Aug 05 '15 at 15:36
  • the "static access" I was talking about was a wrapper for `getBean()` for instantiating beans. the Provider does quite the same, or am I missing something ? – Nati Aug 05 '15 at 15:42
  • 1
    `Provider` is a dependency injected into your object which allows you to solve the lifecycle mismatch between the object it provides and your object. It is like a tailor-made factory object. That's quite unlike a global static method which returns the entire ApplicationContext. – Marko Topolnik Aug 05 '15 at 15:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/85217/discussion-between-nati-and-marko-topolnik). – Nati Aug 05 '15 at 15:46

0 Answers0