Spring项目用JUnit调试时出现错误 Failed to load ApplicationContext 的解决方法(不一定适合所有人)

之前在Spring中加载配置文件**.xml文件的时候,我是写在一个main()方法里面

public class SoundMain {
    /* 基于XML的配置实现Bean自动化装配 */
    public static void  main(String[] args){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/sound.xml");
        //CompactDisc sgt = context.getBean(SgtPeppers.class);
        //sgt.play();
        CDPlayer cdPlayer = context.getBean("CdPlayer",CDPlayer.class);
        cdPlayer.play();
    }
}

但是我最近在 JUnit测试的时候,相同的代码在@Test注解的方法里面就报错了,代码如示

@RunWith(SpringJUnit4ClassRunner.class)
public class ExtraTest {
    @Test
    public void TestEncore(){
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/spring-config.xml");
        ExtraClass ec = ctx.getBean("extraClass", ExtraClass.class);
        ec.out();
    }
}

**.xml的路劲是没有问题的,报的错是:Neither GenericXmlContextLoader nor AnnotationConfigContextLoader was able to load an ApplicationContext from [MergedContextConfiguration@81560cc testClass = ExtraTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]].

And java.lang.IllegalStateException: Failed to load ApplicationContext

最后我发现是因为我加了 @RunWith(SpringJUnit4ClassRunner.class)注解的缘故:这个注解会在测试开始的时候自动创建Spring的应用上下文,在用了这个注解的情况下,可以用@ContextConfiguration(locations="classpath:/spring-config.xml")

去掉@RunWith(...)注解的话,前面的代码也是可以运行的。

因为用new ClassPathXmlApplicationContext()它也会获取Spring的上下文环境,所以会有冲突。下面是用注解的形式的代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/spring-config.xml")
public class ExtraTest {
    @Resource
    private ExtraClass ec;
    @Test
    public void TestEncore(){ ;
        ec.out();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40672761/article/details/83859084