views:

136

answers:

3

I've recently started learning the Spring Framework, and I'm a bit unclear on how the ApplicationContext is supposed to be used - in both standalone and web applications. I understand that the ApplicationContext, once instantiated with the spring configuration xml, is the "spring container" and is a singleton.

But:

  1. In the starting point - main method - of an app do I use ApplicationContext.getBean("className") and then rely on DI for all other registered beans or is there a way to use only DI?
  2. Is there any other place besides the main method where I could/should use ApplicationContext.getBean("className")?
  3. If and when should ApplicationContext.getBean("className") be used in a web app?
  4. If in your opinion there is information I MUST know regarding DI related to web applications, even though I may not of specifically inquired about it, please share.
+1  A: 

I generally recommend only one usage of ApplicationContext.getBean() per application, and rely on the Spring configs to do the rest.

The exception applies in unit tests, where I want to load up a particular subset of beans (so I would explicitly load a bean that normally would be loaded from the top of my bean hierarchy).

Brian Agnew
+3  A: 
  1. You need at least one call into the context from outside it, there's no avoiding that. With webapps, that part is hidden from you, and it it feels like everything is using DI, even though Spring's servlet glue code is doing some unpleasantness behind the scenes.

  2. Could, yes; should, no. There are very few good reasons for calling getBean yourself.

  3. The most obvious scenario is when you have a servlet filter that needs access to the context. FIlters aren't managed by Spring, and so cannot have stuff wired into them by Spring.

  4. That's a bit too vague. Read the reference docs :)

skaffman
Thanks for specifically addressing each of my questions. As for my last question, it was intended as a catch-all for any big pitfalls and misconceptions I as a novice to Spring (DI in web apps) maybe susceptible to and should be aware of. Currently, I've been reading Spring in Action and the ref docs :-)
Ari