Alex
Alex

Reputation: 4073

Recommended way to access Spring beans in Apache Tomcat webapp?

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();

Upvotes: 1

Views: 2479

Answers (2)

towe75
towe75

Reputation: 1470

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.

Upvotes: 1

G__
G__

Reputation: 7111

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!

Upvotes: 0

Related Questions