实现aware接口的bean被spring实例化后可以获取相应的资源,实现BeanFactoryAWare接口可以获取BeanFactory的实例,
示例:
实现BeanFactoryAWare接口
package com.test.springmvc.test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
public class TestAware implements BeanFactoryAware {
private BeanFactory beanFactory;
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public void test() {
MainTest mainTest = (MainTest) beanFactory.getBean("mainTest");
mainTest.test();
}
}
测试类:
package com.test.springmvc.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class MainTest {
public static void main(String[] args) throws Exception {
BeanFactory fb = new XmlBeanFactory(new ClassPathResource(
"applicationContext.xml"));
TestAware test = (TestAware) fb.getBean("testAware");
test.test();
}
public void test() {
System.out.println("hello test beanFactoryAeare");
}
}
可以在控制台打印出
hello test beanFactoryAeare