随笔 - 103  文章 - 1  评论 - 81  阅读 - 46万

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   熊哥club  阅读(5201)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

熊哥club Fork me on GitHub
点击右上角即可分享
微信分享提示