解决 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 {
}

猜你喜欢

转载自www.cnblogs.com/kinome/p/9628830.html