<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	>
<channel>
	<title>Comments on: Setter injection versus constructor injection and the use of @Required</title>
	<atom:link href="http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/</link>
	<description>The voice of SpringSource</description>
	<pubDate>Sun, 05 Jul 2009 20:54:07 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<item>
		<title>By: George Anderson</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-146045</link>
		<dc:creator>George Anderson</dc:creator>
		<pubDate>Wed, 11 Feb 2009 18:54:12 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-146045</guid>
		<description>I use setter dependency injection in my big project and constructor injection really do bother me because although this is just an application, our architecture uses a lot of inheritance and interfaces to accomplish things.

By the way, I can see one class with 40 or more dependencies. This is what we call a Façade.

Best regards,
George.</description>
		<content:encoded><![CDATA[<p>I use setter dependency injection in my big project and constructor injection really do bother me because although this is just an application, our architecture uses a lot of inheritance and interfaces to accomplish things.</p>
<p>By the way, I can see one class with 40 or more dependencies. This is what we call a Façade.</p>
<p>Best regards,<br />
George.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Nikhil Vasaikar</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-119641</link>
		<dc:creator>Nikhil Vasaikar</dc:creator>
		<pubDate>Thu, 04 Sep 2008 08:36:02 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-119641</guid>
		<description>The xml config for @Mandatory did not come up, this time posting without the angular brackets

bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"
		p:requiredAnnotationType="Mandatory"</description>
		<content:encoded><![CDATA[<p>The xml config for @Mandatory did not come up, this time posting without the angular brackets</p>
<p>bean class=&#034;org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor&#034;<br />
		p:requiredAnnotationType=&#034;Mandatory&#034;</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Nikhil Vasaikar</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-119639</link>
		<dc:creator>Nikhil Vasaikar</dc:creator>
		<pubDate>Thu, 04 Sep 2008 08:31:12 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-119639</guid>
		<description>Create your custom annotaion:-

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Mandatory {
}

Register this annotation with the RequiredAnnotationBeanPostProcessor



You can now use @Mandatory on the setter methods.</description>
		<content:encoded><![CDATA[<p>Create your custom annotaion:-</p>
<p>@Retention(RetentionPolicy.RUNTIME)<br />
@Target(ElementType.METHOD)<br />
public @interface Mandatory {<br />
}</p>
<p>Register this annotation with the RequiredAnnotationBeanPostProcessor</p>
<p>You can now use @Mandatory on the setter methods.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Andrew Feller</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-118036</link>
		<dc:creator>Andrew Feller</dc:creator>
		<pubDate>Fri, 22 Aug 2008 19:51:02 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-118036</guid>
		<description>Aside from constructor injection, how else can someone ensure objects are in valid states without coupling it to Spring?  I have avoided @Required and initializingBean interface because I will have to take the same classes later and plug them into a different framework that doesn't use it.</description>
		<content:encoded><![CDATA[<p>Aside from constructor injection, how else can someone ensure objects are in valid states without coupling it to Spring?  I have avoided @Required and initializingBean interface because I will have to take the same classes later and plug them into a different framework that doesn&#039;t use it.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Bert van Brakel</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-113000</link>
		<dc:creator>Bert van Brakel</dc:creator>
		<pubDate>Mon, 14 Jul 2008 07:21:21 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-113000</guid>
		<description>Oh, and using the seperate FooOpts concreate class instead of the interface is easier for spring integration, as you just create another config entry for the FooOpts bean, and pass that in as a constructor arg to the Foo bean.</description>
		<content:encoded><![CDATA[<p>Oh, and using the seperate FooOpts concreate class instead of the interface is easier for spring integration, as you just create another config entry for the FooOpts bean, and pass that in as a constructor arg to the Foo bean.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Bert van Brakel</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-112999</link>
		<dc:creator>Bert van Brakel</dc:creator>
		<pubDate>Mon, 14 Jul 2008 07:14:09 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-112999</guid>
		<description>My preference for beans with a long list of constructors args is to use a configuration bean. As in

public class Foo{
    private final Service service;
    private final SomethingElse somethingElse;

    public Foo(FooOptions opts){
        assert( null != opts  );
  
        service = opts.service;
        somethingElse = opts.somethingElse;
        //don't perform checks on opts, instead on local vars, as callers may have changed opts in the meantime
        assert( null != service );
        assert( null != somethingElse );
    }
}

public class FooOptions{
    public Service service;
    public SomethingElse somethingElse;
    get/set....
}

You could also use the getters/setters in the options bean.

IMHO the advantage of this approach is that if subclasses need further args, just subclass the options bean, and no further changes to your classes are required.

It would be nice if Java supported automatic generation of constructor options beans (ie like named arguments I guess), or allowed inner classes without the need for an instance of the outer class so that these options can be kept in the same file.

Another approach is using an interface:

public class Foo {
	public Foo(FooOpts opts) {
                //..assert(...)
		service = opts.getService();
                somethingElse = opts.getSomethingElse();
                //..assert(...)
	}

	public interface FooOpts {
		public SomethingElse getSomethingeElse();
		public Service getService();
	}
}

and an example usage might be:

Foo foo = new Foo(new Foo.FooOpts(){
	public Service getService() {				
		return "My Service";
	}
	public SomethingElse getSomethingElse() {				
		return "SomethingElse";
	}
});


My personal take on setters vs constructors, is that the setters clutter up the API you are trying to expose, and you also end up with a lot of boring boilerplate get/set. IMHO objects should expose business logic, and not all the other junk for settings the object up. In the case of an options object, it doesn't contain any business logic, its just a transfer object, in which case get/set is fine and doesn't add to the confusion</description>
		<content:encoded><![CDATA[<p>My preference for beans with a long list of constructors args is to use a configuration bean. As in</p>
<p>public class Foo{<br />
    private final Service service;<br />
    private final SomethingElse somethingElse;</p>
<p>    public Foo(FooOptions opts){<br />
        assert( null != opts  );</p>
<p>        service = opts.service;<br />
        somethingElse = opts.somethingElse;<br />
        //don&#039;t perform checks on opts, instead on local vars, as callers may have changed opts in the meantime<br />
        assert( null != service );<br />
        assert( null != somethingElse );<br />
    }<br />
}</p>
<p>public class FooOptions{<br />
    public Service service;<br />
    public SomethingElse somethingElse;<br />
    get/set&#8230;.<br />
}</p>
<p>You could also use the getters/setters in the options bean.</p>
<p>IMHO the advantage of this approach is that if subclasses need further args, just subclass the options bean, and no further changes to your classes are required.</p>
<p>It would be nice if Java supported automatic generation of constructor options beans (ie like named arguments I guess), or allowed inner classes without the need for an instance of the outer class so that these options can be kept in the same file.</p>
<p>Another approach is using an interface:</p>
<p>public class Foo {<br />
	public Foo(FooOpts opts) {<br />
                //..assert(&#8230;)<br />
		service = opts.getService();<br />
                somethingElse = opts.getSomethingElse();<br />
                //..assert(&#8230;)<br />
	}</p>
<p>	public interface FooOpts {<br />
		public SomethingElse getSomethingeElse();<br />
		public Service getService();<br />
	}<br />
}</p>
<p>and an example usage might be:</p>
<p>Foo foo = new Foo(new Foo.FooOpts(){<br />
	public Service getService() {<br />
		return &#034;My Service&#034;;<br />
	}<br />
	public SomethingElse getSomethingElse() {<br />
		return &#034;SomethingElse&#034;;<br />
	}<br />
});</p>
<p>My personal take on setters vs constructors, is that the setters clutter up the API you are trying to expose, and you also end up with a lot of boring boilerplate get/set. IMHO objects should expose business logic, and not all the other junk for settings the object up. In the case of an options object, it doesn&#039;t contain any business logic, its just a transfer object, in which case get/set is fine and doesn&#039;t add to the confusion</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Peter Lawrey</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-49855</link>
		<dc:creator>Peter Lawrey</dc:creator>
		<pubDate>Wed, 19 Sep 2007 21:24:42 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-49855</guid>
		<description>My preference is to use constructors for manditory arguments and IntelliJ's @NotNull annotation to check arguments which cannot be null. I also use setters for optional arguments. (With @NotNull as approriate)

Does anyone know how to configure Spring to use the Common Annotations 1.0 which come with Java 6. e.g. @PostConstruct, @PreDestroy, @Resource and @ConstructorProperties ?</description>
		<content:encoded><![CDATA[<p>My preference is to use constructors for manditory arguments and IntelliJ&#039;s @NotNull annotation to check arguments which cannot be null. I also use setters for optional arguments. (With @NotNull as approriate)</p>
<p>Does anyone know how to configure Spring to use the Common Annotations 1.0 which come with Java 6. e.g. @PostConstruct, @PreDestroy, @Resource and @ConstructorProperties ?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Alef Arendsen</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-48357</link>
		<dc:creator>Alef Arendsen</dc:creator>
		<pubDate>Fri, 14 Sep 2007 09:37:11 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48357</guid>
		<description>Hey Chris,

thanks for your comments. I'll try to update the blog post when I have time, because mentioning the possibility to mix constructor injection and setter injection is definitely something that should have been done from the start.</description>
		<content:encoded><![CDATA[<p>Hey Chris,</p>
<p>thanks for your comments. I&#039;ll try to update the blog post when I have time, because mentioning the possibility to mix constructor injection and setter injection is definitely something that should have been done from the start.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Chris Beams</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-48323</link>
		<dc:creator>Chris Beams</dc:creator>
		<pubDate>Fri, 14 Sep 2007 07:08:54 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48323</guid>
		<description>Looks like my XML example from the comment above got treated as HTML.  Here it is again (very simple, just demonstrating combining constructor and setter injection within a single bean declaration):

&lt;bean id="blogCommenter" class="org.example.BlogCommenter"&gt;
    &lt;constructor-arg value="Chris"/&gt; &lt;!-- first name, required --&gt;
    &lt;constructor-arg value="Beams"/&gt; &lt;!-- last name, required --&gt;
    &lt;property value="S"/&gt; &lt;!-- middle initial, optional --&gt;
&lt;/bean&gt;</description>
		<content:encoded><![CDATA[<p>Looks like my XML example from the comment above got treated as HTML.  Here it is again (very simple, just demonstrating combining constructor and setter injection within a single bean declaration):</p>
<p>&lt;bean id=&#034;blogCommenter&#034; class=&#034;org.example.BlogCommenter&#034;&gt;<br />
    &lt;constructor-arg value=&#034;Chris&#034;/&gt; &lt;!&#8211; first name, required &#8211;&gt;<br />
    &lt;constructor-arg value=&#034;Beams&#034;/&gt; &lt;!&#8211; last name, required &#8211;&gt;<br />
    &lt;property value=&#034;S&#034;/&gt; &lt;!&#8211; middle initial, optional &#8211;&gt;<br />
&lt;/bean&gt;</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Chris Beams</title>
		<link>http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/comment-page-1/#comment-48322</link>
		<dc:creator>Chris Beams</dc:creator>
		<pubDate>Fri, 14 Sep 2007 07:02:46 +0000</pubDate>
		<guid isPermaLink="false">http://blog.interface21.com/main/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/#comment-48322</guid>
		<description>Alef,

Thanks for the thoughtful treatment of these two alternatives.  Constructor vs. setter injection is something that often becomes a matter of religion.  It's not nearly so black-and-white, and I think that (amongst your other points) drawing a distinction between the needs of application code vs. framework code is spot on.  While I strongly prefer constructor injection whenever appropriate, there are certainly contexts where setter injection is preferable (optional parameters are the obvious case here).  It's worth pointing out that these two approaches are not mutually exclusive either.  I often mix and match constructor and setter injection, e.g.:


     &lt;!-- first name, required --&gt;
     &lt;!-- last name, required --&gt;
     &lt;!-- middle initial, optional --&gt;


This is an overly simple example (one would likely never declare such a bean), but it expresses the idea.

As you mention, it translates to Java code that properly leverages constructors to ensure an object is always in a valid state:

BlogCommenter commenter = new BlogCommenter("Chris", "Beams");
commenter.setMiddleInitial('S');

This reduces the likelihood of NullPoninterExceptions down the road, and specifies a clear contract to users of your class as to how it should be used.  No guesswork as to which setters 'must' be called, etc.  These benefits, IMHO, outweigh the decreased readability caused by the fact that constructor args do not have names in the spring configuration XML, particularly because classes may be used in contexts outside Spring configuration.  In these cases, we want to rely on the language as much as possible to inform us about how to use the class.  Constructors are the natural choice here.

Now, if only the p: namespace allowed for some syntactic sugar around constructor args ;-)

- Chris</description>
		<content:encoded><![CDATA[<p>Alef,</p>
<p>Thanks for the thoughtful treatment of these two alternatives.  Constructor vs. setter injection is something that often becomes a matter of religion.  It&#039;s not nearly so black-and-white, and I think that (amongst your other points) drawing a distinction between the needs of application code vs. framework code is spot on.  While I strongly prefer constructor injection whenever appropriate, there are certainly contexts where setter injection is preferable (optional parameters are the obvious case here).  It&#039;s worth pointing out that these two approaches are not mutually exclusive either.  I often mix and match constructor and setter injection, e.g.:</p>
<p>     <!-- first name, required --><br />
     <!-- last name, required --><br />
     <!-- middle initial, optional --></p>
<p>This is an overly simple example (one would likely never declare such a bean), but it expresses the idea.</p>
<p>As you mention, it translates to Java code that properly leverages constructors to ensure an object is always in a valid state:</p>
<p>BlogCommenter commenter = new BlogCommenter(&#034;Chris&#034;, &#034;Beams&#034;);<br />
commenter.setMiddleInitial(&#039;S');</p>
<p>This reduces the likelihood of NullPoninterExceptions down the road, and specifies a clear contract to users of your class as to how it should be used.  No guesswork as to which setters &#039;must&#039; be called, etc.  These benefits, IMHO, outweigh the decreased readability caused by the fact that constructor args do not have names in the spring configuration XML, particularly because classes may be used in contexts outside Spring configuration.  In these cases, we want to rely on the language as much as possible to inform us about how to use the class.  Constructors are the natural choice here.</p>
<p>Now, if only the p: namespace allowed for some syntactic sugar around constructor args <img src='http://blog.springsource.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /><br />
- Chris</p>
]]></content:encoded>
	</item>
</channel>
</rss>
