SpringBoot Service层测试时用@Autowired注入为空值

问题说明:

最近学习了一下SpringBoot,编写一个测试项目时发现在Service中使用的@Autowired注解自动注入的值在测试时,出现空指针异常;

java.lang.NullPointerException
	at com.will.glob.willglob.Service.impl.AritcleDaoImpl.getOneById(AritcleDaoImpl.java:34)
	at com.will.glob.willglob.WillGlobApplicationTests.contextLoads(WillGlobApplicationTests.java:27)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)

错误测试代码如下:

    @Test
    @Transactional
    public void contextLoads() {
        ArticleDao articleDao=new AritcleDaoImpl();
        Article article=new Article();
        article=articleDao.getOneById(1L);
        System.out.println(article);
    }

ArticleDao接口的实现类代码如下:

@Service
public class AritcleDaoImpl implements ArticleDao {
    @Autowired
    ArticleRepository articleRepository;
    @Autowired
    CommRepository commRepository;
    @Autowired
    UsersRepository usersRepository;

    @Override
    public Article getOneById(Long artId) {
        Article article=new Article();

        article=  articleRepository.getOne(artId);
        System.out.println(article);
        return article;
    }
  }

最后debug之后发现用@Autowired注入的几个JPA接口全是空值;注入失败:
注入值为空值
最后在往常查了半天,发现原来是因为我在测试类中使用service层接口ArticleDao的方法是通过new的方式加入的:

而这种方式不能将AritcleDaoImpl()实现类交由SpringBoot接管,但是该类中通过@Autowired注入的几个接口都必须通过Spring容器接管才能自动注入,所以自然就无法注入值了;

解决方法:

既然使用了SpringBoot来开发,那最好就是尽善尽美的利用它设定的方便途径,将接口之类的,全部用@Autowired注解进行注入的方式,来交给Spring托管:

    @Autowired
    ArticleDao articleDao;
    @Test
    @Transactional
    public void contextLoads() {
        Article article=new Article();
        article=articleDao.getOneById(1L);
        System.out.println(article);
    }

测试截图:
在这里插入图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值