Home  >  Q&A  >  body text

java - 为什么spring不支持接口注入

ioc有三种注入方式:setter、构造、接口。为什么spring不支持接口方式注入啊?

搜到的答案,大概是:接口注入模式因为历史较为悠久,在很多容器中都已经得到应用。但由于其在灵活性、易用性上不如其他两种注入模式,因而在 IOC 的专题世界内并不被看好。

还有没有其他的原因呢?

PHPzPHPz2711 days ago784

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:38:46

    Spring’s documentation says:

    DI exists in two major variants, Constructor-based dependency
    injection and Setter-based dependency injection.

    My understanding is that interface injection is actually implemented through setter injection:

    interface InjectPerson {
        public void injectHere(Person p);
    }
    
    class Company implements InjectPerson {
       Person injectedPerson; 
    
       public void injectHere(Person p) {
            this.injectedPerson = p;
        }
    }
    

    reply
    0
  • Cancelreply