Spring Learning note constructor-based or setter-based DI?

Source: Internet
Author: User

If it is a forced dependency, then use the constructor injection and, if it is an optional dependency, use the Set method. Spring encourages constructor injection to ensure that a dependency is not null.

Since you can mix constructor-based and setter-based DI, it's a good rule of thumb to use constructors for mandatory Dependencies and Setter methods or configuration methods for optional dependencies. Note that use of the @Required annotation on a setter method can be used to make the property a Required dependency.

The Spring team generally advocates constructor injection as it enables one to implement application components as Immutable objects and to ensure the required dependencies is not null . Furthermore constructor-injected components is always returned-to-client (calling) code in a fully-initialized state. As a side note, a large number of constructor arguments is a bad code smell , implying that the class likely have t OO Many responsibilities and should is refactored to better address proper separation of concerns.

Setter injection should primarily only being used for optional dependencies so can be assigned reasonable default values WI Thin the class. Otherwise, Not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is this setter methods make objects of the that class amenable to reconfiguration or re-inject Ion later. Management through JMX MBeans is therefore a compelling use case for setter injection.

Use the DI style which makes the most sense for a particular class. Sometimes, when dealing with Third-party classes for which you does not have the source, the choice are made for you. For example, if a Third-party class does not expose any setters methods, then constructor injection Le form of DI.

Spring Learning note constructor-based or setter-based DI?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.