BeanFactory vs ApplicationContext

matt b picture matt b · Oct 28, 2008 · Viewed 243k times · Source

I'm pretty new to the Spring Framework, I've been playing around with it and putting a few samples apps together for the purposes of evaluating Spring MVC for use in an upcoming company project. So far I really like what I see in Spring MVC, seems very easy to use and encourages you to write classes that are very unit test-friendly.

Just as an exercise, I'm writing a main method for one of my sample/test projects. One thing I'm unclear about is the exact differences between BeanFactory and ApplicationContext - which is appropriate to use in which conditions?

I understand that ApplicationContext extends BeanFactory, but if I'm just writing a simple main method, do I need the extra functionality that ApplicationContext provides? And just exactly what kind of extra functionality does ApplicationContext provide?

In addition to answering "which should I use in a main() method", are there any standards or guidelines as far as which implementation I should use in such a scenario? Should my main() method be written to depend on the bean/application configuration to be in XML format - is that a safe assumption, or am I locking the user into something specific?

And does this answer change in a web environment - if any of my classes needed to be aware of Spring, are they more likely to need ApplicationContext?

Thanks for any help. I know a lot of these questions are probably answered in the reference manual, but I'm having a hard time finding a clear breakdown of these two interfaces and the pros/cons of each without reading thru the manual with a fine-tooth comb.

Answer

Miguel Ping picture Miguel Ping · Oct 28, 2008

The spring docs are great on this: 3.8.1. BeanFactory or ApplicationContext?. They have a table with a comparison, I'll post a snippet:

Bean Factory

  • Bean instantiation/wiring

Application Context

  • Bean instantiation/wiring
  • Automatic BeanPostProcessor registration
  • Automatic BeanFactoryPostProcessor registration
  • Convenient MessageSource access (for i18n)
  • ApplicationEvent publication

So if you need any of the points presented on the Application Context side, you should use ApplicationContext.