解决 spring-test 出现 Failed to load ApplicationContext 的异常

 

在使用spring-test的时候,在启动@Test的方法时,spring-test会去加载spring的配置文件,这个时候如果配置文件没有在 @ContextConfiguration 中写全,就会导致加载到一半失败,然后抛出 java.lang.IllegalStateException: Failed to load ApplicationContext 的异常,进而导致优先加载的各种bean加载失败

 

异常:

[main] WARN org.springframework.web.context.support.GenericWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'assetParser' defined in file [D:\project2\RM\target\classes\org\kinome\rm\utils\file\AssetParser.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.kinome.rm.utils.file.AssetParser]: Constructor threw exception; nested exception is java.lang.NullPointerException
[main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@f2f2cc1] to prepare test instance [MvcTest@6d469831]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)

 

 

解决方法:

只需要在 @ContextConfiguration 中把(idea)resources下的所有spring配置文件名写齐全,就不会因为加载不到没写的spring配置文件而加载失败了,写全就能成功加载完所有的配置文件进而全部加载成功了

例:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:spring-servlet.xml"}) // 这里因为没有把 applicationContext-quartz.xml 配置文件加载进去,所以导致了异常的发生
public class MvcTest {
}

 

只需要把 applicationContext.xml 改成 applicationContext*.xml 就可以把 applicationContext-quartz.xml 加载进来了,就能正常运行了。

以后如果再增加了新的spring文件,也得注意在spring-test的 @ContextConfiguration 中引入进来。

以后我会把spring的配置文件全部统一格式为:applicationContext(追加其他命名用来区别spring配置文件).xml ,这样一来,一个 applicationContext*.xml 就全部引入进来了,都不需要改web.xml 和 spring-test 或者其他依赖spring配置文件的需要引入的引入项 的引入了。

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext*.xml", "classpath:spring-servlet.xml"}) 
public class MvcTest {
}

 

转载于:https://www.cnblogs.com/kinome/p/9628830.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值