欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java詳細講解依賴注入的方式

 更新時間:2022年06月22日 11:15:12   作者:ifredom  
Idea中使用@Autowire注解會出現(xiàn)提示黃線,強迫癥患者看著很難受,使用構(gòu)造器注入或者setter方法注入后可解決,下面我們一起來看看

Spring中的三種依賴注入方式

  • Field Injection :@Autowired注解的一大使用場景就是Field Injection
  • Constructor Injection :構(gòu)造器注入,是我們?nèi)粘W顬橥扑]的一種使用方式Setter Injection:
  • Setter Injection也會用到@Autowired注解,但使用方式與Field Injection有所不同,F(xiàn)ield Injection是用在成員變量上,而Setter Injection的時候,是用在成員變量的Setter函數(shù)上
// 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.是否進行循環(huán)依賴檢測

  • Field Injection:不檢測
  • Constructor Injection:自動檢測
  • Setter Injection:不檢測

可能遇到的問題

循環(huán)依賴報錯: 當服務(wù)A需要用到服務(wù)B時,并且服務(wù)B又需要用到服務(wù)A時,Spring在初始化創(chuàng)建Bean時,不知道應(yīng)該先創(chuàng)建哪一個,就會出現(xiàn)該報錯。

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

如果使用構(gòu)造方式注入,能夠精準的提醒你是哪兩個類產(chǎn)生了循環(huán)依賴 .異常報錯信息能夠迅速定位問題:

循環(huán)報錯解決辦法是使用 @Lazy注解 ,對任意一個需要被注入Bean添加該注解,表示延遲創(chuàng)建即可。

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

以上就是Java詳細講解依賴注入的方式的詳細內(nèi)容,更多關(guān)于Java依賴注入的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論