Searching...
Thursday, 25 September 2014

Spring ApplicationContextAware Example

06:15

Spring provides ApplicationContextAware interface to get the ApplicationContext anywhere in our code. In order to get this feature we need to implement ApplicationContextAware interface in our beans and override setApplicationContext method.

Here is one example to get the context from CustomerGroup bean.

Customer.java

public class Customer {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Customer [name=" + name + "]";
    }


}

CustomerGroup.java

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

public class CustmerGroup implements ApplicationContextAware {
   
    ApplicationContext context;
    public ApplicationContext getContext() {
        return context;
    }

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

}

Application-context.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
    <bean id="customer" class="com.pretech.test.Customer">
        <property name="name" value="Vinod Kumaran" />
    </bean>
    <bean id="customerGroupBean" class="com.pretech.test.CustmerGroup" />
</beans>

Test class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class AppContextMain {
 
    public static void main(String[] args) {
 
 
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "application-context.xml");
 
        CustmerGroup customerGroupBean = (CustmerGroup) context
                .getBean("customerGroupBean");
 
        //Getting context from customerGroup bean and getting customer from that context
        System.out.println(customerGroupBean.getContext().getBean(Customer.class));
    }
 
}

Output

Customer [name=Vinod Kumaran

0 comments: