Powered by Blogger.

Friday, 6 June 2014

BeanNameAware and BeanFactoryAware

By Unknown  |  10:57 No comments

BeanNameAware and BeanFactoryAware


The first one makes the object aware of their bean name in a bean factory.
The second interface gives the bean access to the Bean Factory that created it.


  1. The xxxAware interface is a common pattern used within the Spring framework. They are typically used to allow a Spring managed bean to be given an object (via the interfaces setXxx method) at Spring bootstrap time.
  2. Springs documentation says this about the Aware interface, which is a super interface to the two you mention:
  3. Marker superinterface indicating that a bean is eligible to be notified by the Spring container of a particular framework object through a callback-style method.

public class HelloWorld  implements BeanNameAware, BeanFactoryAware{
       private String msg;

       public String getMsg() {
              return msg;
       }

       public void setMsg(String msg) {
              this.msg = msg;

       }

       @Override
       public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
               System.out.println("received the beanFactory " + beanFactory);
             
       }

       @Override
       public void setBeanName(String name) {
               System.out.println("the name of the bean is " + name);
             

       }
}

Bean definition


<bean id="messanger" class="com.shambhu.bean.HelloWorld">
      <property name="msg" value="Hello World" />

</bean>

Testing

public class HelloMain {
    public static void main(String[] args) {
ApplicationContext beanFactory = new ClassPathXmlApplicationContext(
                           "spring-beans.xml");
        HelloWorld messanger = (HelloWorld) beanFactory.getBean("messanger");
        System.out.println(messanger.getMsg());
    }
}

OutPut

Jun 06, 2014 11:22:52 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7dbc345a: startup date [Fri Jun 06 23:22:52 IST 2014]; root of context hierarchy
Jun 06, 2014 11:22:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-beans.xml]
the name of the bean is messanger
received the beanFactory org.springframework.beans.factory.support.DefaultListableBeanFactory@71a7cdd0: defining beans [messanger]; root of factory hierarchy
Hello World



Anonymous Author: Unknown

Hello, I am Author, decode to know more: In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet.

Related Posts

0 comments:

Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates