Spring ApplicationContextAware Example

By Arvind Rai, October 28, 2021
On this page we will learn Spring ApplicationContextAware example. In Spring we can fetch ApplicationContext anywhere in our code with the help of ApplicationContextAware interface. The ApplicationContextAware interface has setApplicationContext() method. To create ApplicationContext aware bean, the class needs to implement ApplicationContextAware interfaceand override setApplicationContext() method. The ApplicationContextAware is used for bean lookup purpose and for those objects which needs to access file resources.

Implement ApplicationContextAware Interface

The ApplicationContextAware has following method.
void setApplicationContext(ApplicationContext applicationContext) throws BeansException 
This method sets the ApplicationContext that this object runs in.

Find the code to use ApplicationContextAware.
ApplicationContextAwareTest.java
package com.concretepage;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextAwareTest implements ApplicationContextAware {
	ApplicationContext context;
	public ApplicationContext getContext() {
		return context;
	}
	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.context=context;
	}
} 

Configure Bean

app-conf.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans.xsd ">
  
    <bean id="testA" class="com.concretepage.A"/>
    <bean id="appcontext" class="com.concretepage.ApplicationContextAwareTest"/>
</beans> 
A.java
package com.concretepage;
public class A {
	public void doTask(){
		System.out.println("Do some task.");
	}
} 

Run Application

SpringTest.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
	public static void main(String[] args) {
		AbstractApplicationContext  context = new ClassPathXmlApplicationContext("app-conf.xml");
		ApplicationContextAwareTest appcontext= (ApplicationContextAwareTest)context.getBean("appcontext");
		ApplicationContext appCon =appcontext.getContext();
		A a= (A)appCon.getBean("testA");
		a.doTask();
		context.registerShutdownHook();
	}
} 
Find the output.
Do some task. 

Reference

Interface ApplicationContextAware

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us