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.- 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 interfacessetXxx
method) at Spring bootstrap time. - Springs documentation says this about the
Aware
interface, which is a super interface to the two you mention: - 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
0 comments: