Thursday, 2 February 2012

ApplicationContextAware and BeanNameAware

 ApplicationContextAware :

Sometimes you need to access your Spring application context from a Spring initialized Bean. For this use case you need to implement the ApplicationContextAware interface. The following code snippets describes the usage:

public class Triangle implements ApplicationContextAware {

    private int a;
    private ApplicationContext context;

    public Point getA() {
        return pointA;
    }
    public void setA(int a) {
        this.a = a;
    }
    public void draw(){
        System.out.println("A= "+a );
    }

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

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
       <bean id="triangle" class="com.example2.Triangle" >
             <property name="a" value="100"></property>
       </bean>
</beans>
 
BeanNameAware :

The Interface BeanNameAware is implemented by beans that help to aware of their bean name in bean factory. The setBeanName method set the name for the bean in the bean factory. In this example you will see how to implement BeanNameAware in your bean class.  


Example : 

DrawingApp.java
public class DrawingApp {

    public static void main(String[] args) {
       
        ApplicationContext context = new ClassPathXmlApplicationContext("
spring.xml");
        Triangle triangle = (Triangle) context.getBean("triangle");
        triangle.draw();
        triangle.setBeanName("triangleBean");
        triangle.showBeanName();
       
    }
}

Triangle.java

public class Triangle implements BeanNameAware {
    int a ;
    String name;
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
    @Override
    public void setBeanName(String name) {
        this.name= name;
    }
    public void showBeanName() {
        System.out.println("Bean Name is "+name);
    }
}

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <bean id="triangle" class="com.example2.Triangle">
         <property name="a" value="100" />
    </bean>
</beans> 

Output : Bean Name is triangleBean

No comments:

Post a Comment