温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot @Autowired注入为空的原因有哪些

发布时间:2023-03-06 16:01:07 来源:亿速云 阅读:181 作者:iii 栏目:开发技术

今天小编给大家分享一下SpringBoot @Autowired注入为空的原因有哪些的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

    @Autowired注入为空的情况解读

    因最近在开发中遇到了使用@Autowired注解 自动装配时,会报空指针,发现对象并没有装配进来,通过查询,总结了几种可能造成这种情况的原因。

    1.最简单的一种情况,查看被装配的类,也就是@Autowired注解下的类是否添加了注解交给SpringBoot托管,@service等注解,或者是直接加上@Component注解。

    2.看你的xxxxxApplication是否在根目录,因为springboot默认扫描的就是启动类下的目录(这个我记着只限于Springboot2.0.5之前的版本,因为新版可以通过@ComponenScan注解去指定扫描范围)。

    3.@Service、@Componet、@Configuration、@Repository等Spring注解未被扫描到,例如:springboot的主类扫描规则,就是说需要查看你的Springboot启动类,xxxxxApplication,查看启动类上注解是否加了@ComponenScan注解,是否指定了扫描范围。

    使用springboot启动类配置扫描的两种注解配置方式:

    • 1、@Controller @EnableAutoConfiguration @ComponentScan 。

    • 2、@SpringBootApplication

    4.使用救急方法,这是如果没找到原因,我们先使用其他方法让程序先能正常运行和调试,后续再查找问题。

    @Autowired
     private SchedulerFactoryBean schedulerFactoryBean;
        
     private static QuartzManager quartzManager;
        
     /**
      * 通过@PostConstruct实现初始化bean之前进行的操作
      * @desc 初始化操作,得到QuartzManager实例
      * @Date 2019年1月7日
      */
     @PostConstruct 
     public void init() {  
          quartzManager = this;  
          quartzManager.schedulerFactoryBean = this.schedulerFactoryBean;        
    }

    使用@PostConstruct 初始化。

    5.这个原因很重要,也是经常会被忽略的一个因素。调用者是new出来的。如果类A中存在成员属性B, B是通过@Autowired自动注入,而类A的实例是通过new的方式产生的,那么自动注入会失效的,此时通过Spring的上下文获取所有的Bean的方法来获取B。此时,看看你在报空指针的那个类,看它是否是被new出来的,如果是,不妨使用SpringUtil.getBean()方法替换下, 然后再试下!

    @Autowired注入bean找不到异常

    异常描述

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field clientAuthService in com.yinhai.mzgh.eurekaclient.feign.interceptor.Oauth3RequestInterceptor 
    required a bean of type 'com.yinhai.mzgh.eurekaclient.feign.service.ClientAuthService' that could not be found.

    The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)


    Action:

    Consider defining a bean of type 'com.yinhai.mzgh.eurekaclient.feign.service.ClientAuthService' in your configuration.

    问题原因

    这个问题是环境问题,在Profiles 中之前是dev 环境

    SpringBoot @Autowired注入为空的原因有哪些

    以上就是“SpringBoot @Autowired注入为空的原因有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI