SpringBoot 测试类无法自动注入@Autowired,测试类报错:NullPointerException

在使用SpringBoot搭建多数据源的时候遇到问题,如图所示:
在这里插入图片描述
虽然这个下划线的红色编译运行不会报错,但是看着很不舒服,将@Autowired换成了@Resource注解就可以了,但是具体原因还有待考究,有大佬知道可以评论一下。

运行测试类,一直报错:

java.lang.NullPointerException…太多了,不想粘贴

空指针问题本来我以为是上面的@Autowired问题,换成了@Resource还是不行。
在网上找了一些解决方案可以看一下:
https://blog.csdn.net/howard789/article/details/81020233
https://www.cnblogs.com/qingmuchuanqi48/p/11886618.html
这种解决方案不适合我这种问题。

后来才发现不能在测试类创建实例对象,贴上错误代码:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDataApplication.class)
class SpringbootDataApplicationTests {
    @Test
    void contextLoads() {
        VideoConfigService videoConfigService = new VideoConfigService();
        List list = videoConfigService.findAllId();
        System.out.println(list.size());
    }

}

正确代码:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDataApplication.class)
class SpringbootDataApplicationTests {

    @Autowired
    private VideoConfigService videoConfigService;
    @Test
    void contextLoads() {
        List list = videoConfigService.findAllId();
        System.out.println(list.size());
    }

}

写的比较杂乱,上班期间,继续工作了。
有问题,还请大佬指出。

你可能感兴趣的:(Java)