最近遇到一個奇怪的問題。maven項目再進行junit單元測試的時候發現無法加載配置文件。一會能加載一會又不能加載。然后試了在src/main/resource下面的配置文件放到src/test/resource下,這樣每次都能加載了。
但是理論上不用放在test下也是可以加載的。
package com.xsw.test; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import com.xsw.model.TeamsDTO; import com.xsw.service.CreditService; import com.xsw.service.TeamService; @RunWith(SpringJUnit4ClassRunner.class) // 表示繼承了SpringJUnit4ClassRunner類 @ContextConfiguration(locations = { "classpath:spring.xml" ,"classpath:spring-mybatis.xml"}) public class MybatisTest { private static Logger logger = Logger.getLogger(MybatisTest.class); @Resource private CreditService creditService; @Resource private TeamService teamService; @Test public void testTeam(){ TeamsDTO cre = teamService.getTeamById(1L); logger.info(JSON.toJSON(cre)); } }


后來發現用eclipse進行編譯的時候 指向maven install 有時mapping文件和配置文件無法編譯到target目錄下。為什么老是有這種偶然現象呢?
為了每次都能編譯正確,在pom下強制配置 進行編譯 配置如下。放在最后
</build> </project>
之前就可以了
<!--編譯之后包含xml--> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> </project>
