美文网首页
记一次Spring Junit4测试的无法注入bean的错误

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

作者: whoisje | 来源:发表于2018-07-19 12:05 被阅读0次

    我是分模块开发的,模块之间相互依赖,在使用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层也可以。
    粗心真的是浪费时间,越是细枝末节越要做好。加油!

    相关文章

      网友评论

          本文标题:记一次Spring Junit4测试的无法注入bean的错误

          本文链接:https://www.haomeiwen.com/subject/wuttmftx.html