Sunday, June 12, 2011

Spring ApplicationContext within Servlet

If you want to use Spring-managed beans within you web application, especially Servlet controller and you don't know which implementation of ApplicationContext to use I recommend you to use XmlWebApplicationcontext. This is pretty straightforward as all you have to do is write 4 lines of code (I love Spring ;) - the following lines of code:
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setServletContext(getServletContext());
ctx.setConfigLocations(new String[] { beans definition locations });
ctx.refresh();

Beans definition locations are paths relative to the web root i.e. if you store your bean definitions in WEB-INF/META-INF/services/descriptor.xml you should provide exactly the same string as a config location.

Don't forget to invoke refresh() method.

That's all - isn't Spring beautiful?

No comments:

Post a Comment

Chitika