好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

spring中使用@Autowired注解无法注入的情况及解决

spring @Autowired注解无法注入

问题简述

在使用spring框架的过程中,常会遇到这种两情况:

1、在扫描的包以外使用需要使用mapper

2、同目录下两个controller或者两个service,在使用@Autowired注解注入mapper或者service时,其中一个可以注入,另一个却为空。

原因:(此处只说第二种)

楼主在经过调试后发现,在框架启动的过程中,此注解其实是注入过的,并非没有注入,只是在其后某处抹除了,至于原因,原谅楼主能力有限还未弄清楚,欢迎大家指正交流。

解决方案

这里楼主给出一种解决方案,实在无法注入的情况下,我们可以采用工具类的方法来注入:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

@Component    //当前类注解为spring组件

public class AbnormalRateUtil {

  // 定义一个该类的静态变量

  private static AbnormalRateUtil abnormalRateUtil;

  //注入所需mapper

  @Autowired

  private InterFaceInfoMapper interFaceInfoMapper;

  @PostConstruct   //此注解的方法在bean加载前执行

  private void init() {

   abnormalRateUtil = this ;

   abnormalRateUtil.interFaceInfoMapper= this .interFaceInfoMapper;

   //初始化时将静态化的interFaceInfoMapper进行了实例化

  }

  //静态get方法

  public static AbnormalRateUtil getAbnormalRateUtil() {

   return abnormalRateUtil;

  }

  //静态get方法

  public static InterFaceInfoMapper getInterFaceInfoMapper() {

   return abnormalRateUtil.interFaceInfoMapper;

  }

}

调用方式

在使用时可直接通过此工具类进行调用,如下:

?

1

List<InterFaceRuler> ruleList=AbnormalRateUtil.getInterFaceInfoMapper().findRuleById(id);

@Autowired注解注入失败,提示could not autowire

controller层无法调用接口层提示could not autowire的解决办法

主要原因是因为我们的spring检验级别的问题,我们可以通过降低检验的安全级别就可以解决这一问题。

File —> Settings—>Editor—>Inspections—>Spring————》将最右边的Serverity改为Warning

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_20503733/article/details/99671136

查看更多关于spring中使用@Autowired注解无法注入的情况及解决的详细内容...

  阅读:15次