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

最近遇到一个奇怪的问题。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>

 

posted on 2017-06-08 10:54  熊哥club  阅读(5168)  评论(0编辑  收藏  举报

熊哥club Fork me on GitHub