The correct way to load the spring context

We added Spring to a legacy application. We encountered places where we needed access to Spring beans by non-Spring beans. The Spring context was loaded by:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

The appeared to work fine, but what we did not realize until we looked at the logging was that the Spring context was refreshed every time this was called. This is a no-no when you have over 1000 classes under packages to be scanned.

The correct way is by:

ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

This worked for the Servlet API objects. We had some POJOs that did not have access to the Servlet API. We were already performing special processing via a filter to add various objects to the current context by using ThreadLocal.

This entry was posted in Java, Spring and tagged , . Bookmark the permalink.

Leave a comment