记一次Spring Junit4测试的无法注入bean的错误

我是分模块开发的,模块之间相互依赖,在使用Junit4测试Service层的时候发现无法自动注入bean
具体代码如下
首先定义了一个父类BaseServiceTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config/spring-context.xml")
public class BaseServiceTest {
}

里面什么也没有,但是继承父类就不用重复写

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config/spring-context.xml")

这两句了
子类如下

public class BurningChartSpiderTest extends BaseServiceTest {

    @Autowired
    BurningChartSpider burningChartSpider;
    @Test
    public void startSpider() {
        burningChartSpider.startSpider();
    }
}

但是@Autowired总是报错,提示找不到bean,发现是自己,没导入spring的配置文件
但是写@ContextConfiguration(locations = "classpath:spring-config/spring-context.xml")居然没有报错,因为Service模块依赖了dao模块,dao模块中的spring配置文件是存在的,不过只扫描dao模块的包。
Service模块添加spring配置文件就可以,记得扫描Service模块,或者dao模块的配置文件添加扫描Service层也可以。
粗心真的是浪费时间,越是细枝末节越要做好。加油!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容