Java系列 - 依赖注入及相关问题

起因

Idea中使用@Autowire注解会出现提示黄线,强迫症患者看着很难受。
使用构造器注入或者setter方法注入后可解决

Spring中的三种依赖注入方式

  • Field Injection :@Autowired注解的一大使用场景就是Field Injection
  • Constructor Injection :构造器注入,是我们日常最为推荐的一种使用方式
  • Setter Injection: Setter Injection也会用到@Autowired注解,但使用方式与Field Injection有所不同,Field Injection是用在成员变量上,而Setter Injection的时候,是用在成员变量的Setter函数上
// Field Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {
    @Autowired
    private UploadDao uploadDao;

}
// Constructor Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {

    private UploadDao uploadDao;
	UploadServiceImpl(UploadDao uploadDao){
		this.uploadDao = uploadDao;
	}
}
// Setter Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {

    private UploadDao uploadDao;
    
	@Autowired
	public void setUploadDao(UploadDao uploadDao){
		this.uploadDao =uploadDao
	}
}

1.是否进行循环依赖检测

  • Field Injection:不检测
  • Constructor Injection:自动检测
  • Setter Injection:不检测

可能遇到的问题

  1. 循环依赖报错: 当服务A需要用到服务B时,并且服务B又需要用到服务A时,Spring在初始化创建Bean时,不知道应该先创建哪一个,就会出现该报错。
This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example
class ServerA{
	@Autowired
	private ServerB b;
}

class ServerB{
	@Autowired
	private ServerA a;
}

如果使用构造方式注入,能够精准的提醒你是哪两个类产生了循环依赖 .异常报错信息能够迅速定位问题:
在这里插入图片描述

循环报错解决办法是使用 @Lazy注解 ,对任意一个需要被注入Bean添加该注解,表示延迟创建即可。

class ServerA{
	@Autowired
	@Lazy
	private ServerB b;
}

class ServerB{
	@Autowired
	@Lazy
	private ServerA a;
}

------ 如果文章对你有用,感谢 >>>点赞 | 收藏 <<<

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值