Java DI何时不适合使用
我正在读一篇关于DI的博客,有一些句子我不懂 DI在运行时是单例对象,只有spring扫描范围内的对象(使用Java DI何时不适合使用,java,spring,dependency-injection,spring-annotations,Java,Spring,Dependency Injection,Spring Annotations,我正在读一篇关于DI的博客,有一些句子我不懂 DI在运行时是单例对象,只有spring扫描范围内的对象(使用@Component)才能使用DI by annotation(@Autowired),而new创建的其他对象不能使用DI by annotation,这意味着什么 无法使用DI,因为父级可以由new创建 public class Father{ private SonRepository sonRepo; private Son getSon(){r
@Component
)才能使用DI by annotation(@Autowired
),而new创建的其他对象不能使用DI by annotation,这意味着什么
无法使用DI,因为父级可以由new创建
public class Father{
private SonRepository sonRepo;
private Son getSon(){return sonRepo.getByFatherId(this.id);}
public Father(SonRepository sonRepo){this.sonRepo = sonRepo;}
}
可以使用DI,因为父工厂是由系统生成的单例对象
@Component
public class FatherFactory{
private SonRepository sonRepo;
@Autowired
public FatherFactory(SonRepository sonRepo){}
public Father createFather(){
return new Father(sonRepo);
}
这意味着:
- Spring负责管理对象的范围。您不需要带有静态getInstance方法的类似样板文件的最终类。(关于单身人士如何在春天工作。)
- Spring只能将内容自动连接到组件中,如果这些组件位于它被告知要查看的位置,那么组件扫描就是Spring搜索它需要连接的组件的方式。您可以指定spring需要从哪些包名开始搜索,从而为spring提供起点。如果一个组件不在这些目录中,那么Spring将无法管理它