在使用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 { }
