AppclicationContextWare实现对象public class MyApplicationContext implements ApplicationContextAware, InitializingBean {
public MyApplicationContext() {
// TODO Auto-generated constructor stub
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
// TODO Auto-generated method stub
System.out.println("ApplicationContextg");
System.out.println("MyApplicationContext: setApplicationContext - " + context.getBean("myApplicationContext").hashCode());
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("初始化对象 - MyApplicationContext");
}
}配置文件<?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="myApplicationContext" class="com.springDemo.aware.MyApplicationContext" />
</beans>测试类@RunWith(BlockJUnit4ClassRunner.class)
public class AwareTest {
DefaultListableBeanFactory factory;
@Before
public void init() {
System.out.println("初始化BeanFactory");
this.factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
ClassPathResource resource = new ClassPathResource("resource/bean-aware.xml");
reader.loadBeanDefinitions(resource);
}
@After
public void destory() {
}
@Test
public void test() {
MyApplicationContext context = (MyApplicationContext)this.factory.getBean("myApplicationContext");
System.out.println("Get Bean: - " + context.hashCode());
}
}输出打印初始化BeanFactory
八月 30, 2017 11:36:39 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [resource/bean-aware.xml]
初始化对象 - MyApplicationContext
Get Bean: - 1165897474可见,能成功拿到对象,InitializingBean的方法也成功调用,那应该是成功实例化了的,但是setApplicationContext就是不调用。为什么
2 回答
蓝黑Frizen
TA贡献1条经验 获得超0个赞
好像把DefaultListableBeanFactory实现的容器改成ClassPathXmlApplicationContext实现就可以了,不知道是不是我写错了什么。
添加回答
举报
0/150
提交
取消