⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 blog.csdn.net/LuQiaoYa/article/details/111573886 「LuQiaoYa」欢迎转载,保留摘要,谢谢!


🙂🙂🙂关注**微信公众号:【芋道源码】**有福利:

  1. RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
  2. RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
  3. 您对于源码的疑问每条留言将得到认真回复。甚至不知道如何读源码也可以请教噢
  4. 新的源码解析文章实时收到通知。每周更新一篇左右
  5. 认真的源码交流微信群。

原因

根本原因在于当Spring框架帮我们管理的时候就会自动的初始化接下来会用到的属性,而通过new对象的方式,在该new对象中使用到的一些实例就需要自己去做初始化,否则就会报空指针异常。

如下例子所示:

TestService 通过@Autowired注入,那么Spring容器就会自动注入TestService 中会用到的TestDao。

如例一所示。

例一

@RestController
@RequestMapping(value = "/test")
public class TestController {

@Autowired
private TestService testService;

@RequestMapping(value = "/print",method = RequestMethod.GET)
public void test() {
testService.test();
}
}



@Service
public class TestService {

@Autowired
private TestDao testDao;

public void test() {
testDao.test();
}
}

如果TestService 通过new对象方式新建的话,Spring容器就不会自动注入TestDao,此时testDao为null,会报空指针异常。此时就需要在TestService中自己new一个TestDao对象。如例二所示。

例二

@RestController
@RequestMapping(value = "/test")
public class TestController {

private TestService testService = new TestService ();

@RequestMapping(value = "/print",method = RequestMethod.GET)
public void test() {
testService.test();
}
}



@Service
public class TestService {

@Autowired
private TestDao testDao;

public void test() {
TestDao testDao = new TestDao ();
testDao.test();
}
}

总结

在程序启动时,Spring会按照一定的加载链来加载并初始化Spring容器中的组件。

例如:在A中注入B,B中注入C。在A中调用B,来使用B中调用C的方法时,如果不采用自动注入,而是使用new对象方式的话,就会报空指针异常(因为B中的C并没有被初始化)。

文章目录
  1. 1. 原因
  2. 2. 例一
  3. 3. 例二
  4. 4. 总结