Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
942 views
in Technique[技术] by (71.8m points)

dependency injection - Setter DI vs. Constructor DI in Spring?

Spring has two two types of DI: setter DI and construction DI.

Constructor-based DI fixes the order in which the dependencies need to be injected. Setter based DI does not offer this.

Setter-based DI helps us to inject the dependency only when it is required, as opposed to requiring it at construction time.

I do not see any other significant differences, as both types of Spring DI provide the same features - both setter and constructor DI inject the dependency when the code starts up. Granted, constructor DI will do it through the constructor while setter DI will do it through a setter right after constructing the object, but it does not make any difference for the developer in terms of performance, etc. Both also offer means to specify the order of dependency injection as well.

I'm looking for a scenario where one provides a distinct advantage over the other or where one type is completely unusable.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When it comes to Spring specific pros and cons:

  • Constructor injection (from the definition) does not allow you to create circular dependencies between beans. This limitation is actually an advantage of constructor injection - Spring can resolve circular dependencies when setter injection is used without you even noticing.

  • On the other hand if you use constructor injection CGLIB is not able to create a proxy, forcing you to either use interface-based proxies or a dummy no-arg constructor. See: SPR-3150


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...