spring 配置文件沒法加載,junit找不到xml配置文件java.lang.IllegalStateException: Failed to load ApplicationContext

最近遇到一個奇怪的問題。maven項目再進行junit單元測試的時候發現沒法加載配置文件。一會能加載一會又不能加載。而後試了在src/main/resource下面的配置文件放到src/test/resource下,這樣每次都能加載了。java

可是理論上不用放在test下也是能夠加載的。spring

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目錄下。爲何總是有這種偶然現象呢?apache

爲了每次都能編譯正確,在pom下強制配置 進行編譯 配置以下。放在最後json

   </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>
相關文章
相關標籤/搜索