Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

ApplicationContextAware interface in Spring

In this article, we will learn why we need ApplicationContextAware and how do we use it.

Spring is an open source framework for Java and J2EE application development. The framework is widely used mainly in enterprise applications. There are several modules of spring available. The application context is one of the important concepts in spring framework. You need to get hold of the application context to get different services inside the framework and use it effectively in application design.

Sometimes it is needed to access context object inside bean class to create another bean. But the context object is created into another class, how we access this context object inside the bean class, once it is created inside the invoking bean factory class. This can be achieved using ApplicationContextAware class instance variable.

ApplicationContextAware in Detail:

There are two kinds of instances created using spring:

  • Singleton
  • Prototype

Singleton instances are created for once at the time of spring container initialization and prototype instances are created every time, whenever it is needed. In this case, to get access of singleton bean instance, there is an interface is defines, which is known as ApplicationContextAware it provides a setter () method that is used to access context variable:

Listing 1: setApplicationContext() method

@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
}

Listing 1 shows a setter method setApplicationContext() that initialize the ApplicationContext variable with context instance of the bean class created by spring container.

Listing 2: Triangle.java

package com.springmvcapp.controller;

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

public class Triangle implements ApplicationContextAware, BeanNameAware{
	private String type;
	private int height;
	private String beanName;
	
	public String getBeanName() {
		return beanName;
	}
	
	private ApplicationContext context = null;
	
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	public ApplicationContext getContext() {
		return context;
	}
	public void setContext(ApplicationContext context) {
		this.context = context;
	}
	public String draw(){
		System.out.println(this.context.getBean("triangle"));
		return getType() + " Triangle Drawn";	
	}
	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.context = context;
	}
	@Override
	public void setBeanName(String beanName) {
		this.beanName = "Bean Name is : " + beanName;
	}
}

Listing 2 defines a java bean class Triangle.java that implements two interfaces ApplicationContextAware and BeanNameAware and implements its methods setApplicationContext() and getBeanName(). The getBeanName () provides the name of singleton bean name and getApplicationContext() initializes the ApplicationContext type variable name to singleton bean class instance created at the time of spring container initialization.

Listing 3: HelloWorld.java

package com.springmvcapp.controller;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorld {
	   @RequestMapping("/triangle")
       public ModelAndView triangle() {
    	   String message = "<br><div align='center'><h1>Triangle.<h1><br>";
    	   ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    	   Triangle obj = (Triangle) context.getBean("triangle");
    	   
    	   message += obj.getBeanName() + "<br/>";
    	   message += obj.draw();
    	   
           return new ModelAndView("welcome", "message1", message);
      }
}

Listing 3 defines the HelloWorld.java class file. This class file defines the spring mvc controller that is annotated by @Controller annotation that is defined in org.springframework.stereotype.Contoller class. This class defines url mapping to “triangle” using annotation @RequestMapping, which is defined into class org.springframework.web.bind.annotation.RequestMapping class. A method name triangle () has been created that returns ModelAndView type instance. This method creates an instance of Triangle class using ApplicationContext class instance and call getBeanName () and draw() methods of class Triangle and append their results to String type variable “message”.

Now let’s define spring.xml file in Listing 4:

Listing 4: spring.xml

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="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 = "triangle" class = "com.springmvcapp.controller.Triangle">
    	<property name="type" value="test"/>
    </bean>
</beans>

Listing 4 defines a spring.xml configuration file into the class folder that defines doctype tag and tag. tag contains its sub tag that defines a “triangle” bean and set its property for class type variable name “type” to its default value “test”.

Let’s define springmvcapp-servlet.xml configuration file in Listing 5:

Listing 5: springmvcapp-servlet.xml

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="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">

    <context:component-scan base-package="com.springmvcapp.controller" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Listing 5 defines springmvcapp-servlet.xml file that defines a <beans> tag. This <beans> tag defines its sub-tags <context:component-scan> with its attribute base-package name that indicates controller to be loaded, while deploying application. The <bean> tag, sub-tag of <beans> tag defines the “viewResolver” id type tag that hits the class name “org.springframework.web.servlet.view.UrlBasedViewResolver”. This tag defines the <property> tag to its name “viewClass” and its value class “org.springframework.web.servlet.view.JstlView”. Its next two property tags also define “prefix” and “suffix” for the view file and its directory.

Let’s define index.jsp in Listing 6:

Listing 6: index.jsp

<html>
<head>
<title>Application Context Aware App | Index</title>
</head>
<body>
	<br>
	<div align='center'>
	<h2>
		WELCOME TO Application Context Aware APP     
		<a href="triangle.html">Load Triangle</a>
	</h2>
	</div>
</body>
</html>

Listing 6 defines index.jsp file that creates the default view of spring mvc application. It displays the default message “Welcome to Application Context Aware App” and gives a anchor tag url “triangle.html” that hits default controller method “triangle()” and loads its message defines into the Listing 7:

Listing 7: welcome.jsp

<html>
<head>
    <title>Spring MVC App</title>
</head>
<body>
    ${message1}
</body>
</html>

Listing 7 defines welcome.jsp file that displays the message passed from the triangle() method of the default loaded controller java class.

Required Tools & Applications:

To create this application, we are required to have following application listed and set of jar files shown in Figure 1:

  • Eclipse IDE (Eclipse Juno)
  • Application Server (Tomcat Apache)
  • JDK Environment (JDK 7)
  • Set of Spring Jar files shown in Figure 1
Set of required Spring Jar Files

Figure 1: Set of required Spring Jar Files

Directory structure created for this application by the Eclipse IDE is shown into the Figure 2:

 Directory Structure created for the Spring MVC web application by the Eclipse IDE

Figure 2: Directory Structure created for the Spring MVC web application by the Eclipse IDE

Figure 2 shows the directory structure created by Eclipse IDE for the Spring MVC web application.

Once the application has been deployed on the application server, the default page index.jsp will be loaded into the web browser, shown into the Figure 3:

index.jsp page loaded into the web browser after application deployment

Figure 3: index.jsp page loaded into the web browser after application deployment

Figure 3 displays the index.jsp page that displays the default message with an anchor tag url “trianagle.html” that hits to method triangle() of the default controller HelloWorlds.java class as shown into the Figure 4:

triangle.html page loaded

Figure 4: triangle.html page loaded

Figure 4 displays the triangle.html page created by the triangle () method of the HelloWorld.java class. This page shows the bean name using:

BeanNameAware interface method getBeanName () and Also get the clone of singleton created bean using ApplicationContextAware interface using its method getApplicaitonContext().

Conclusion

In this article, we learn about the need of ApplicationContextAware and BeanNameAware. We also went through an example using Spring MVC web application that created a clone instance of singleton bean class instance into the Triangle.java bean class.



Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login