一个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>
本文详细介绍了如何在Java中利用Spring框架的ApplicationContextAware接口,通过实现ApplicationContextAware接口并重写setApplicationContext方法,从而在类中获取到ApplicationContext的引用,进而操作或访问应用程序上下文中注册的其他Bean。
1356

被折叠的 条评论
为什么被折叠?



