Spring ApplicationContext

Last modified on August 1st, 2014 by Joe.

In this tutorial we will what is spring ApplicationContext and how to access it. There are numerous different ways to get a task done in Spring framework and that is one advantage of it.

What is ApplicationContext?

ApplicationContext is an interface for providing configuration information to an application. There are multiple classes provided by springframework that implements this interface and helps us use configuration information in applications. ApplicationContext provides standard bean factory lifecycle capabilities. An important capability which we will be using in below code example is, class implementing ApplicationContext should scan for ApplicationContextAware beans and invoke setApplicationContext by passing an implementation of its instance.

ApplicationContext vs BeanFactory

BeanFactory is a subset of ApplicaitonContext and provides lesser functionalities. When we need full capabilities with respect to configuration handling then we go for ApplicationContext.

How to access ApplicationContext inside a java bean?

To get access to ApplicationContext we should implement ApplicationContextAware interface in the respective java bean. It has a method,


void setApplicationContext(ApplicationContext applicationContext)
                           throws BeansException

The ApplicationContext implementation which we are using in our application will invoke this method and pass the concrete object for AppplicationContext. Using this we can get access to all the configuration information.

In the case of spring web application we have a utility class provided by spring framework called WebApplicationContextUtils.


ServletContext servletContext = this.getServletContext();

WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

We can use this utility to get application context but we need to provide the respective servletcontext as parameter. Following source code demonstrates how we can get access to application context even from inside a simple plain java bean where we don’t have access to servlet context.

Sample to Access ApplicationContext

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="applicationContextUtils" class="com.javapapers.spring.ApplicationContextUtils"></bean>

	<bean id="helloWorld" class="com.javapapers.spring.HelloWorld" />

	<bean id="strHelloWorld" class="java.lang.String">
		<constructor-arg value="Hello World" />
	</bean>

</beans>

ApplicationContextUtils.java

We will create the following utility class, it implements ApplicationContextAware and provides the setApplicationContext which will be invoked by spring container and the applicationContext will be passed by it. We store it in a static variable and expose it through a get method so that it can be accessed all through the application.

package com.javapapers.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextUtils implements ApplicationContextAware {

	private static ApplicationContext ctx;

	@Override
	public void setApplicationContext(ApplicationContext appContext)
			throws BeansException {
		ctx = appContext;

	}

	public static ApplicationContext getApplicationContext() {
		return ctx;
	}
}

HelloWorld.java

This is a simple java bean which uses our utility method to get access to the ApplicationContext.


package com.javapapers.spring;

import org.springframework.context.ApplicationContext;

public class HelloWorld {

	public String getValueFromContext(String beanName) {
		ApplicationContext appCtx = ApplicationContextUtils
				.getApplicationContext();
		String strFromContext = (String) appCtx.getBean(beanName);
		return strFromContext;
	}
}

TestAppContext.java

This example is based on a simple java application (not a web application). It uses ClassPathXmlApplicationContext which implements ApplicationContext.

package com.javapapers.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAppContext {

	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				"META-INF/spring-context.xml");
		HelloWorld hw = (HelloWorld) appContext.getBean("helloWorld");

		String output = hw.getValueFromContext("strHelloWorld");
		System.out.print(output);
	}
}

Download Example Source Code

SpringAppCtx

Lazy-instantiation and ApplicationContext

By default spring implementations of ApplicationContext eagerly instantiate all the singleton beans at startup. This helps us to ensure all the configuration and dependencies are intact. This default behaviour can be customized as below by just adding property lazy-init=”true”.


<bean id="lazy" class="com.javapapers.LazyBean" lazy-init="true"/>

When the ApplicationContext is starting up this bean will not be instantiated and configured.

Annotation Based Access

Spring 2.5 onwards we can autowire the ApplicationContext as well as BeanFactory as below,

private @Autowired ApplicationContext appContext;
private @Autowired BeanFactory beanFactory;

Comments on "Spring ApplicationContext"

  1. Anonymous says:

    very nice explanation.. Keep up your good work…

  2. Mahesh Varma says:

    Very nice explanation and easy to understand…. Keep going…

  3. Anonymous says:

    Your posts are encouraging to use various practices. Hats off to the work you are doing for the java world!! I’ve been following your blogs quite a long and i’ve subscribed it as well.

    I’ve one suggestion, to kindly add more Spring Core related blogs and add the “…/category/spring/” context of your blogs in the menu item as well, like Core Java, JSP, Servlet, Design Patterns…

    As of now it requires search with Spring, javapapers as keywords on net to land up on the spring related blogs of yours.

    It’s not about the topics or anything, you sense of humor, using the right images at the right time, using the right writings at the right time is outstanding. Keep up the good work, Joe.

    Thanks.

  4. Giri Kanchukota says:

    It is very simple to understand. Thanks for sharing your information.

  5. Rashmit says:

    Hi Joe,

    As always I appreciate your efforts in making the Java Simple. Wonderful topic & nice clean approach of expatiation..Keep it up.

  6. Anonymous says:

    very gud tutorial to understand

  7. morteza says:

    thanks! very helpful!!
    why we need to use application context from ApplicationContextUtils in web app ?

    can we just get application context by implement ApplicationContextAware interface in the respective java bean?

  8. Sandeep Singh says:

    Thank you Joe .. Really helpful

  9. vikas patil says:

    very nice….thanks…

  10. S L N V Praveen says:

    as usual… nice Joe….

  11. sanjib says:

    Hi J2EE/ APP are not properly tagged.

  12. Anonymous says:

    Please change your photo

  13. Anonymous says:

    This post is really useful to everyone

  14. vipin says:

    Hi, I have implemented this method to get the ApplicationContext but I am facing one strange issue . Some time it works fine and some time, it throws the exception .

    I spent a lot of time to figure out the cause but couldn’t get any clue . Please help .

    java.lang.IllegalStateException: BeanFactory not initialized or already closed – call ‘refresh’ before accessing beans via the ApplicationContext
    at org.springframework.context.support. AbstractRefreshableApplicationContext.getBeanFactory (AbstractRefreshableApplicationContext.java:172)
    at org.springframework.context.support. AbstractApplicationContext.getBean (AbstractApplicationContext.java:1093)
    at com.vzw.emp.reports.util.SpringApplicationContext. getBean(SpringApplicationContext.java:18)
    at com.vzw.emp.reports.compiler.ReportHelper.updateUniqueUserData(ReportHelper.java:77)
    at

  15. jason says:

    Very Good explanation.Finally i got to know about ApplicationContextAware after reading different atricles posted by others. good one.

  16. SAM says:

    Excelllent Tutorial

  17. Ponic says:

    Nice tutorial. Good

  18. Anonymous says:

    Hi vipin, This problem arises because you have mixed the various versions of spring jars.like 2.5.6 and 3.x like that.

  19. Anonymous says:

    good post

  20. Anonymous says:

    Hi Joe,

    Is there a way to access member variable of a spring singleton bean in HttpSessionListener

    ApplicationContext ctx =
    WebApplicationContextUtils.
    getWebApplicationContext(session.getServletContext());
    ProductObject productObject =
    (ProductObject) ctx.getBean(“com.product.ProductObject”);

    ProductObject has a member variable HashMap
    , this is what I am trying to access

    Appreciate your help if you could give me some leads

    Thanks

  21. Panda says:

    Very nice explanation BeanFactory actually used in case of small systems like mobile devices development , where limited resources are available like CPU cycle and memory , but application context is not sub set of BeanFactory :)

  22. swetha says:

    hi Joe..
    Your explanation on appliationContext proved extremely useful to me.
    Very Nicely written!
    Awaiting more articles !:)

  23. k says:

    nice

  24. Anonymous says:

    I’m satisfied by the info u have mentioned above!!!

  25. sam says:

    thanks a lot for providing such precious post..
    thank u so much…

  26. Jie says:

    Why is lib folder is empty, JARS and class folders on build path are missing. Cannot debug the project. How can I debug the project

  27. Joe says:

    Jie,
    1. You have to add the required jars. I am not able to bundle the jars, as the file size will be toooo huge.
    2. You need to compile the source and generate the class file. I thought, as part of learning process you will do it :-)

  28. g1 says:

    >>why we need to use application context from ApplicationContextUtils in web app ?

    I needed to in one case … I had a bean injected initialized to some default values in the spring application-context.xml, but in my Action class, needed to change some of the attributes (as per the values in the HttpRequest) … so retrieved the bean from AppContext, made a defensive copy and set the required values.

    HTH.

  29. Vasiliy says:

    step with dependencies is missing

  30. SuJeet Pillai says:

    Awesome content. I was in urgent need of working on some modules and I was brain-fried when I saw the term Application Context in each class. I tried to make some sense and understand it from the name but it was not very helpful.
    Your article was very helpful. It helped me understand without going into the details of its methods or hierarchies.
    Thanks.
    Although, a suggestion:
    Sometimes a pictorial representation or a side link or a downloadable file to the hierarchies of a class, method and constructor lists etc will be very helpful.
    That will make your posts a one stop solution.

    Thanks again. :-)

  31. Anonymous says:

    nice description

  32. Gaurav Bajpai says:

    hey Joe, thx for this really helpful article…

    but I have a Question…

    You said that if we are adding property lazy-init=”true” then the bean will not load at the starting of ApplicationContext… so when it will initialize actually ??

  33. Tarun says:

    nice description easy to understand thaanks..

  34. Tarun says:

    nice description easy to understand thanks..

  35. avdhesh samele says:

    good….thanks*

  36. Anthony says:

    Great post – thanks for the info!

  37. Maddy says:

    Hi Joe,
    I want to add one element value from jsp form in to context, and retrieve that value on another jsp page. So, kindly help me how should i do this?

  38. anil says:

    can you plz explain what is purpose of applicationContext.xml

  39. Dhananjay says:

    Nice way ! Thanks a lot for sharing… :)

  40. rama says:

    Tell me the use of ApplicationContextAware Interface

  41. Anonymous says:

    The above explanation is on spring core,

  42. Anonymous says:

    Do you want to add the value to contex??

  43. Ganesh says:

    Nice & helpful description!!!!!

  44. Steve Johann says:

    Very nice presentation – thank you for your time!

  45. Fareed Mohammed says:

    its is really good article

  46. Ehsan says:

    Great tutorial Joe…..
    thanks.

Comments are closed for "Spring ApplicationContext".