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>
作者:熊哥club
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明。文章部分内容来源网络,如有版权问题,请留言告知,博主会尽快删除.
微信扫描下方二维码关注【熊哥club】,回复1024获取程序员必备IT电子书,回复java获取全套学习资源


分类:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?