spring中读取资源文件两种方式及应用场景

 

1.  利用ClassPathXmlApplicationContext  java 代码

Code:
  1. ApplicationContext context = new ClassPathXmlApplicationContext("beanConfig.xml");    
  2. HelloBean helloBean = (HelloBean)context.getBean("helloBean");      
  3. System.out.println(helloBean.getHelloWorld());   

2.利用 FileSystemResource类读取,注意这里的类均来自于spring相关的jar包

Code:
  1. Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/beanConfig.xml");      
  2.  BeanFactory factory = new XmlBeanFactory(rs);      
  3. HelloBean helloBean = (HelloBean)factory.getBean("helloBean");      
  4. System.out.println(helloBean.getHelloWorld());      

 场景:上边的两种方法通常运用于项目的单元测试中。第一种方法在我没有使用Maven开放的项目中经常使用。在dao层,service层采用这种方法,配置文件通常在classes目录下,ClassPathXmlApplicationContext()可以很方便的找到。

     第二种方法通常使用于采用Maven管理的项目中。因为项目中每一层都是依赖关系,ClassPathXmlApplicationContext()方法无法查找到classes下的配置文件,需要采取第二种方法。FileSystemResource类属于spring包。

    

你可能感兴趣的:(spring中读取资源文件两种方式及应用场景)