【问题标题】:When is DI not suitable to useDI什么时候不适合使用
【发布时间】: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


【解决方案1】:

意思是:

  • Spring 负责管理对象的范围。您不需要像具有静态 getInstance 方法的最终类这样的样板。 (关于单例在 Spring 中的工作方式see this question。)

  • 只有当那些组件位于它被告知要查看的某个地方时,Spring 才能将这些东西自动连接到组件中,组件扫描是 spring 搜索它需要连接的组件的方式。您可以通过指定开始搜索所需的包名称来为 spring 提供起点。如果组件不在这些目录之一中,则 Spring 无法管理它。

【讨论】:

  • 非常感谢您的回答。在你回答的提示下,我搜索了@Component 的用法。带有这个注解的类是由spring管理的,spring管理的对象默认范围是单例的。 DI 只能用于那些是单例对象的对象,而不是那些由 new 创建的对象。这就是博客这么说的原因。我理解正确吗?
  • @climy:我想是的。组件和 Bean 都是 spring 管理的,区别见Spring: component vs bean
猜你喜欢
  • 2011-09-13
  • 1970-01-01
  • 2019-02-28
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 2011-03-10
  • 2019-09-17
相关资源
最近更新 更多