1. 利用ClassPathXmlApplicationContext java 代码
- ApplicationContext context = new ClassPathXmlApplicationContext("beanConfig.xml");
- HelloBean helloBean = (HelloBean)context.getBean("helloBean");
- System.out.println(helloBean.getHelloWorld());
2.利用 FileSystemResource类读取,注意这里的类均来自于spring相关的jar包
- Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/beanConfig.xml");
- BeanFactory factory = new XmlBeanFactory(rs);
- HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
- System.out.println(helloBean.getHelloWorld());
场景:上边的两种方法通常运用于项目的单元测试中。第一种方法在我没有使用Maven开放的项目中经常使用。在dao层,service层采用这种方法,配置文件通常在classes目录下,ClassPathXmlApplicationContext()可以很方便的找到。
第二种方法通常使用于采用Maven管理的项目中。因为项目中每一层都是依赖关系,ClassPathXmlApplicationContext()方法无法查找到classes下的配置文件,需要采取第二种方法。FileSystemResource类属于spring包。