springboot @Autowired bean注入失败解决方案

项目中常常会踩到一些莫名其妙的坑,而且怎么发生的为什么发生的怎么解决的,让一些萌新都很懵。有一些不仅是萌新看了一脸懵,就连老手看了也一脸懵,然后一步一步debug看debug走 hahahhaha~可见原理底层的重要性!

1.ServiceImpl实现类注入Mapper为null时,确定Mapper是否加类注解@Mapper并检查Service实现类是否添加类注解@Service。

2.Controller注入Service为null时,确定Service实现类是否添加类注解@Service。

如图:
在这里插入图片描述
在这里插入图片描述

3.执行类/工具类/定时任务 @Autowired注入Service抛空指针异常,使用@Component与@PostConstruct

@Component : 把普通pojo实例化到spring容器中
@PostConstruct :PostConstruct在构造函数之后执行,只会执行一次
如图:
在这里插入图片描述
原理:先执行的是静态方法,这个时候@Autowired注入的组件还没有完成所以是null,然后执行
@PostConstruct的init进行初始化,这个时候bean已经注入进来,给赋值一下就好了!

4.项目框架或其他莫名其妙的问题导致Controller层注入Service失败

对于这种情况,网上早有些解决方案,而我采用的也是写一个直接去类取bean的工具类:实现ApplicationContextAware接口,定义一个静态的ApplicationContext(Spring应用上下文环境)
下面直接发代码:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component("springContextUtils")
public class SpringContextUtils implements ApplicationContextAware {
    /**
     * Spring应用上下文环境
     */
    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     *
     * @param applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /**
     * 根据class获取对应的bean对象
     * @param clz
     * @return
     */
    public static Object getBean(Class<?> clz){
        return applicationContext.getBean(clz);
    }
}

调用:

取bean:
BrokenPointService brokenPointService = (BrokenPointService) SpringContextUtils.getBean(BrokenPointService.class);
 
方法内调用:
brokenPointService.xxxx(xxx);
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值