SpringBoot 中@Autowired 注入失效原因及解决方法

1、原因分析

  • 1.1 包没有被扫描到

      通过@Autowired注入的类所在的包路径不在Application启动类所在的包/子包路径下。
      Spring Boot项目的Bean装配默认规则是根据Application类(指项目入口类)所在的包位置从上往下扫描。
      eg: Application启动类在包com.alibaba.taobao下,则只会扫描com.alibaba.taobao包及其所有子包,如果需要自动装载的类所在包不在com.alibaba.taobao及其子包下,而是在com.alibaba.tmall下,则不会被扫描,自然就没法被注入!

  • 1.2 代码中使用new关键字创建实例

      若类A中包含成员属性B, B是通过@Autowired自动注入,而类A的实例是通过new的方式产生,则自动注入会失效的。

2、针对上述的解决方法

  • 2.1 添加包扫描

       在启动类中定义分别扫描两个包 ,即在@SpringBootApplication注解的类中添加:

@ComponentScan({"com.alibaba.taobao","com.alibaba.tmall"})

       或

@ComponentScan({"com.alibaba"})
  • 2.2 通过Spring上下文工具类获取bean

        定义一个SpringUtil类

/**
 * Spring上下文工具类,用以让普通类获取Spring容器中的Bean
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;
    
    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }
    
    //通过name获取 Bean     
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
}

       然后在类A中通过如下调用获取Spring容器中的B实例

ClassBInterface b = (ClassBInterfaceImpl) SpringUtil.getBean("classBInterfaceImpl");

 

 

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值