软件编程
位置:首页>> 软件编程>> java编程>> spring中使用@Autowired注解无法注入的情况及解决

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

作者:王志威-yc  发布时间:2023-06-10 21:48:24 

标签:spring,@Autowired,注解,注入

spring @Autowired注解无法注入

问题简述

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

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

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

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

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

解决方案

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


@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;
}
}

调用方式

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


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

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

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

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

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

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

来源:https://blog.csdn.net/qq_20503733/article/details/99671136

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com