Article:
  Twelve Best Practices For Spring XML Configurations
Subject:   Constructor args vs properties
Date:   2008-07-14 07:37:28
From:   Benoit Sanchez
I believe that defining beans via constructor args is far less powerful than property injection.
The main reason is circular reference between beans. Suppose A must know B and B must know A, how could you do with constructors ?!
I think constructor args should be avoided for this reason.
Main Topics Oldest First

Showing messages 1 through 1 of 1.

  • Constructor args vs properties
    2009-01-18 21:18:42  Me [View]

    This isn't a reason at all to avoid constructor injection altogether. There are arguments for an against using constructor injection, but it certainly has its place.

    I use constructor injection where the mandatory fields are not too high in number. Non-mandatory fields can still be injection via setters in addition. This also makes it obvious which fields are mandatory when reading configuration, and allows you to define the mandatory fields as final in your Java class.

    Where there is a possible circular-reference issue, move this property to setter injection with a comment above that bean config. It's common sense stuff really and keeps it tidy.

    As for autowiring I tend to agree that it seems more trouble than it's worth. Being explicit makes it easy to maintain and is not as restrictive if a new bean of that type is created. ByName just doesn't seem worth the possible confusion.