两个原因导致Spring @Autowired注入的组件为空

本文分析了在Spring框架中,如果@Autowired注解的组件实例化手动而非由Spring管理,可能导致NullPointerException。原因包括手动创建服务类和未正确使用组件注解。解决方法是确保所有依赖项通过Spring自动注入。
摘要由CSDN通过智能技术生成

public interface MyRepository extends CrudRepository<My, Long> {

List findByName( String name );

}

你好,2005呼叫并要求返回他们的代码。好吧,IoC就像是街上的帅小伙子一样,如果你使用的是Spring(自动注入),则需要一直使用它。这是Controller, Service 和 Repository的代码片段,它们将导致NullPointerException。

@Controller

public class Controller {

@GetMapping(“/example”)

public String example() {

MyService my = new MyService();

my.doStuff();

}

}

@Service

public class MyService() {

@Autowired

MyRepository repo;

public void doStuff() {

repo.findByName( “steve” );

}

}

当它尝试访问MyRepository自动连接的存储库时,这将在Service中引发NullPointerException,这不是因为Repository的连接有任何问题,而是因为你使用MyService my = new MyService()手动实例化了MyService。要解决此问题,需要自动注入MyService:

@Controller

public class Controller {

@Autowired

MyService service;

@GetMapping(“/example”)

public String example() {

service.doStuff();

}

}

@Service

public class MyService() {

@Autowired

MyRepository repo;

public void doStuff() {

repo.findByName( “steve” );

}

}

@Repository

public interface MyRepository extends CrudRepository<My, Long> {

List findByName( String name );

}

你忘记在某个类使用组件注解或者它的扩展注解


Spring使用组件扫描来查找需要自动注入并放入到IoC容器中的类。基本上,Spring将扫描项目的类路径(或你指定的路径),找到所有@Component注解的类并将其用于自动装配。因此,如果你忘记注解一个类,则该类将不能自动注入,当你尝试使用它时,将得到一个空的实例,从而导致NullPointerException。

@ Service,@ Repository和@Controller都是@Component特殊情景下的子注解,因此要自动注入的任何类都必须使用其中之一进行注释。否则,自动注入将导致实例为空:

public class MyService {

public void doStuff() {

}

}

这样的是没有问题的:

@Service

public class MyService {

public void doStuff() {

}

}


本文仅是阅读英文文档练手,原文如下:

原文

====================================================================

Two reasons why your Spring @Autowired component is null

The Spring framework makes heavy use of Inversion of Control (IoC) to let you inject classes without having to worry about their scope, lifetime or cleanup.

A common error people hit is when they autowire a class and when they try to call a method on it find that it is null and they get a NullPointerException. So why didn’t Spring auto-wire your class for you? Here’s two possible reasons:

YOU INSTANTIATED THE A CLASS MANUALLY


Hi, 2005 called and asked for their code back. Yeah, OK, IoC is like the cool kid on the block and if you are using Spring then you need to be using it all the time. Here’s a code snippet of a Controller, Service and Repository that will result in a NullPointerException.

@Controller

public class Controller {

@GetMapping(“/example”)

public String example() {

MyService my = new MyService();

my.doStuff();

}

}

@Service

public class MyService() {

@Autowired

MyRepository repo;

public void doStuff() {

repo.findByName( “steve” );

}

}

@Repository

public interface MyRepository extends CrudRepository<My, Long> {

List findByName( String name );

}

This will throw a NullPointerException in the service class when it tries to access the MyRepository auto-wired Repository, not because there is anything wrong with the wiring of the Repository but because you instantiated MyService() manually with MyService my = new MyService(). To fix this auto-wire the Service as well:

@Controller

public class Controller {

@Autowired

MyService service;

@GetMapping(“/example”)

public String example() {

service.doStuff();

}

}

@Service

public class MyService() {

@Autowired

MyRepository repo;

public void doStuff() {

repo.findByName( “steve” );

}

}

@Repository

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

知其然不知其所以然,大厂常问面试技术如何复习?

1、热门面试题及答案大全

面试前做足功夫,让你面试成功率提升一截,这里一份热门350道一线互联网常问面试题及答案助你拿offer

2、多线程、高并发、缓存入门到实战项目pdf书籍

3、文中提到面试题答案整理

4、Java核心知识面试宝典

覆盖了JVM 、JAVA集合、JAVA多线程并发、JAVA基础、Spring原理、微服务、Netty与RPC、网络、日志、Zookeeper、Kafka、RabbitMQ、Hbase、MongoDB 、Cassandra、设计模式、负载均衡、数据库、一致性算法 、JAVA算法、数据结构、算法、分布式缓存、Hadoop、Spark、Storm的大量技术点且讲解的非常深入


《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
发、JAVA基础、Spring原理、微服务、Netty与RPC、网络、日志、Zookeeper、Kafka、RabbitMQ、Hbase、MongoDB 、Cassandra、设计模式、负载均衡、数据库、一致性算法 、JAVA算法、数据结构、算法、分布式缓存、Hadoop、Spark、Storm的大量技术点且讲解的非常深入**

[外链图片转存中…(img-s8v8CXQ3-1713446903653)]

[外链图片转存中…(img-CafEF3w4-1713446903653)]

[外链图片转存中…(img-R96RSW3U-1713446903653)]
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值