【发布时间】:2019-08-25 05:37:40
【问题描述】:
我正在阅读有关 DI 的博客,其中有些句子我不明白。
DI在运行时是一个单例对象是什么意思,只有在spring的扫描范围内的对象(带有@Component)可以通过注解(@Autowired)使用DI,而其他对象通过new创建不能通过注解使用DI?
不能使用 DI,因为父亲可以由 new 创建。
public class Father{
private SonRepository sonRepo;
private Son getSon(){return sonRepo.getByFatherId(this.id);}
public Father(SonRepository sonRepo){this.sonRepo = sonRepo;}
}
可以使用DI,因为FatherFactory是系统生成的单例对象。
@Component
public class FatherFactory{
private SonRepository sonRepo;
@Autowired
public FatherFactory(SonRepository sonRepo){}
public Father createFather(){
return new Father(sonRepo);
}
【问题讨论】:
-
欢迎来到 Stack Overflow。请不要包含可能以正确格式包含在您的帖子中的文本图像。
标签: java spring dependency-injection spring-annotations