一个bean可以实现BeanFactoryAware接口的方式获得一个他所在BeanFactory的引用。同样,也可以通过实现ApplicationContextAware接口获得他在ApplicationContext的引用。
配置:
- public class ContextAwareDemo implements ApplicationContextAware {
- private ApplicationContext ctx;
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- ctx = applicationContext;
- }
- public static void main(String[] args) {
- ApplicationContext ctx = new ClassPathXmlApplicationContext(
- "/META-INF/spring/acdemo1-context.xml");
- ContextAwareDemo demo = (ContextAwareDemo) ctx.getBean("contextAware");
- demo.displayAppContext();
- }
- public void displayAppContext() {
- 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>