一个bean可以实现BeanFactoryAware接口的方式获得一个他所在BeanFactory的引用。同样,也可以通过实现ApplicationContextAware接口获得他在ApplicationContext的引用。
配置:
- publicclassContextAwareDemoimplementsApplicationContextAware {
- privateApplicationContext ctx;
- publicvoidsetApplicationContext(ApplicationContext applicationContext)
- throwsBeansException {
- ctx = applicationContext;
- }
- publicstaticvoidmain(String[] args) {
- ApplicationContext ctx =newClassPathXmlApplicationContext(
- "/META-INF/spring/acdemo1-context.xml");
- ContextAwareDemo demo = (ContextAwareDemo) ctx.getBean("contextAware");
- demo.displayAppContext();
- }
- publicvoiddisplayAppContext() {
- System.out.println(ctx);
- }
- }
配置:
- <?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.xsd">
- <bean id="contextAware"class="com.apress.prospring2.ch04.context.ContextAwareDemo"/>
- </beans>