1. package com.test.spring; 2. import org.springframework.beans.factory.BeanFactory; 3. import org.springframework.core.io.Resource; 4. import org.springframework.beans.factory.xml.XmlBeanFactory; 5. public class BeanFactoryUsage { 6. public static void main(String[] args){ 7. //从文件系统资源实例化BeanFactory 8. 9. //默认从当前的工程目录下开始查找(工程目录/com/test/文件目录) 10. org.springframework.core.io.Resource res = new org.springframework.core.io.FileSystemResource("com/test/bean.xml"); 11. org.springframework.beans.factory.BeanFactory factory = new org.springframework.beans.factory.xml.XmlBeanFactory(res); 12. 13. //从classpath下的资源实例化BeanFactory (Eclipse中的src/data目录下) 14. org.springframework.core.io.Resource resClasspath = new org.springframework.core.io.ClassPathResource("data/bean2.xml"); 15. org.springframework.beans.factory.BeanFactory factory2 = new XmlBeanFactory(resClasspath); 16. 17. //使用ApplicationContext从classpath下的xml文件实例化BeanFacotory 18. String classPath = "data/"; 19. org.springframework.context.ApplicationContext appContext = new org.springframework.context.support.ClassPathXmlApplicationContext(new String[]{classPath+"bean2.xml"}); 20. //直接生成类工厂的实例。 21. org.springframework.beans.factory.BeanFactory factory3 = (BeanFactory)appContext; 22. } 23. }