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.5\bin\WEB-INF\jdbc.properties 這個在tomcat啟動的時候,是在bin里面啟動的。他會以bin做為目錄去找你指定的bin下面的WEB-INF\jdbc.properties文件。而classpath不一樣。這是相對路徑。會根據你的項目地址去找web-inf下面的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM