views:

19

answers:

2

I'm developing a web application on Apache Tomcat 6 with Hibernate and Spring, I'm using different XML configuration files to define my Spring beans (like the Hibernate DAO, Quartz scheduler and some other stuff). All these files are loaded at Tomcat start up via web.xml (ContextLoaderListener).

Now I'm not sure what is the recommended way to get access to my beans.

Should I write on class which provides the BeanFactory for all classes which should use a bean, or is it the better way to load the BeanFactory in each class.

BeanFactory bf = (BeanFactory) ContextLoader.getCurrentWebApplicationContext();
A: 

Use dependency injection instead. Create getters & setters in each controller class, and use your *-servlet.xml to inject the required beans via the <property> tag. No factory needed!

Greg Harman
A: 

One of the core ideas of the spring framework is to minimize dependencies between classes. You'll get the most benefit by using this concept throughout your whole project. Each and every backend object should be defined as bean and can therefore use the dependency injection automatism.

If some of your Beans need to access the ApplicationContext directly (eg for requesting all Beans implementing some marker interface) you can implement the ApplicationContextAware interface, so still no factory is needed.

tweber