SpringJUnit4加载类目录下(src)和WEF-INF目录下的配置文件

路径说明:

一、加载类目录下的配置文件

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext_test.xml") 
public class MyTest1 {
    @Autowired
    private Type t;//获取在applicationContext_test.xml中被注入的Type实例
    @Autowired
    private HibernateTemplate hibernateTemplate;//获取在applicationContext_test.xml中被注入的HibernateTemplate实例  //获取Type的实例
    @Test
    public void getTypeInstance(){
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:applicationContext_test.xml"); 
        System.out.println(applicationContext.getBean("type"));//Type [tid=0, tname=testName1, tcontent=无]
    }
    //获取HibernateTemplate的实例
    @Test
    public void getHibernateTemplateInstance(){
        System.out.println(hibernateTemplate);//org.springframework.orm.hibernate3.HibernateTemplate@eb5d53
    }
    
}

二、加载WEF-INF目录下的配置文件

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:WebContent/WEB-INF/config/applicationContext.xml"})    
public class MyTest2{

    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Autowired
    private BasicDataSource dataSource;//获取hibernateTemplate
    @Test
    public void getHibernateTemplate(){
        System.out.println(hibernateTemplate);//org.springframework.orm.hibernate3.HibernateTemplate@17ff08d
    }
    //获取dataSource
    @Test
    public void getDataSource(){
        System.out.println(dataSource);//org.apache.commons.dbcp.BasicDataSource@8f9cc4
        System.out.println(dataSource.getMaxWait());//1000
        System.out.println(dataSource.getMaxActive());//500
    }

}

重点:1.如果开发工具为myeclipse,经测试SpringJUnit4无法无法加载WEF-INF目录下的配置文件。2.即使是eclipse,在加载WEF-INF目录下的配置文件时,无法加载其中的jdbc.properties(Tomcat容器初始化ApplicationContext加载是正常的),故将其移至类目录下。

鸣谢:http://blog.csdn.net/yeohcooller/article/details/7631202

附:关于SpringJUnit4不能加载WEF-INF目录下的jdbc.properties的原因及分析

网友的回答

a君

这个问题是由于你的项目结构决定的,你把abc.properties 放在WEB-INF目录下,无路是在开发环境还是在产品使用环境,这个abc.properties的加载都是问题。 
解决的办法: 
如果可以将abc.properties文件移动到你的源文件目录下,如果你使用maven管理项目,那么缺省是src/main/resources。这样你的applicationContext.xml文件中加载属性可以用 
classpath:path/abc.properties。

 b君

汗。你那在src下面就可以了。在项目发布出去。他会放到web-inf了。楼主,你要考虑一下。src下面的代码是放在那里的。源代码与发布后的代码间的关系。这些你去了解一下。这个问题就解决了。
C:Tomcat 5.5inWEB-INFjdbc.properties 这个在tomcat启动的时候,是在bin里面启动的。他会以bin做为目录去找你指定的bin下面的WEB-INFjdbc.properties文件。而classpath不一样。这是相对路径。会根据你的项目地址去找web-inf下面的
原文地址:https://www.cnblogs.com/wql025/p/4818125.html