<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	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/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Basil Vandegriend: Professional Software Development &#187; Spring</title>
	<atom:link href="http://www.basilv.com/psd/blog/tag/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.basilv.com/psd</link>
	<description></description>
	<lastBuildDate>Thu, 17 May 2012 14:31:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Java-Based Configuration of Spring Dependency Injection</title>
		<link>http://www.basilv.com/psd/blog/2009/java-based-configuration-of-spring-dependency-injection</link>
		<comments>http://www.basilv.com/psd/blog/2009/java-based-configuration-of-spring-dependency-injection#comments</comments>
		<pubDate>Fri, 01 May 2009 12:55:15 +0000</pubDate>
		<dc:creator>Basil Vandegriend</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.basilv.com/psd/?p=353</guid>
		<description><![CDATA[At the heart of the Spring Framework is its dependency injection capabilities provided by its inversion-of-control container. Traditionally the configuration of dependencies has been done in one or more separate XML files. In these files you need to specify code-specific constructs such as the concrete classes to use as implementations of interfaces. It has always [...]]]></description>
			<content:encoded><![CDATA[<p>At the heart of the <a href="http://www.springsource.org/">Spring Framework</a> is its <a href="http://martinfowler.com/articles/injection.html">dependency injection</a> capabilities provided by its inversion-of-control container. Traditionally the configuration of dependencies has been done in one or more separate XML files. In these files you need to specify code-specific constructs such as the concrete classes to use as implementations of interfaces. It has always seemed unnatural to me to do this configuration within XML instead of using Java code. One problem, for example, is that doing renames of your classes or packages will break your XML configuration. Tooling support for these Spring XML files has admittedly helped, but doesn't overcome for me the fundamental inconsistency in using XML to configure Java code. What's wrong with using Java? Traditionally, one significant problem with doing Spring configuration within Java code is that it turned out to be much more verbose than the XML files – the Spring Java APIs were not explicitly designed and optimized to do Java-based configuration. </p>
<p>This state of affairs with Spring configuration changed with the introduction of the <a href="http://www.springsource.org/javaconfig">Spring Java Configuration project</a>, commonly called JavaConfig. JavaConfig provides roughly the same capabilities as Spring's XML-based configuration but uses Java code that is quite compact and readable. I have tried out JavaConfig and I really like it – my unease over XML configuration has been finally laid to rest. Using JavaConfig is fairly simple: you create one or more configuration classes using the conventions expected by JavaConfig, then create an instance of <code>JavaConfigApplicationContext</code> or <code>JavaConfigWebApplicationContext</code> and use it like a regular Spring <code>AppplicationContext</code>.</p>
<p>The most significant decision I think you need to make when using JavaConfig is what approach to use to define dependencies. The approach you choose determines how you go about writing your configuration class. While this decision is not specific to JavaConfig - Spring's standard XML configuration allows for the same set of approaches to be used – the application of each approach using JavaConfig is different. These three approaches to defining dependencies are:</p>
<ol>
<li>Explicit declaration of beans and dependencies.</li>
<li>Automatic dependencies via autowiring.</li>
<li>Automatic beans via component scanning.</li>
</ol>
<p>In the remainder of this article I am going to provide examples using JavaConfig for these three approaches and discuss the pros and cons of each. While the examples focus exclusively on one of the approaches at a time you can easily combine all three approaches within a single configuration class. For the sake of clarity, however, I recommend on real projects to choose one approach as the primary method of configuration. The source code listed in this article is provided in the <em>Java Examples</em> project which can be downloaded from the <a href="http://www.basilv.com/psd/software">Software</a> page.</p>
<p>All three approaches use the same configuration example. There are two beans to configure, each with an interface and an underlying implementation class. The first bean is <code>ResumeRepository</code> which is a Repository class (aka Data Access Object) that provides CRUD-type operations for the domain object <code>Resume</code>. For this example this repository interface only contains a single method <code>Set&lt;Resume&gt; findAll()</code>. The second bean is <code>CalculatorService</code>, which is a Service class that provides functionality relating to resumes:  for this example a single method <code>void validate(Resume)</code>. The Java code for these two interfaces and the domain object is provided below:</p>
<pre class="prettyprint">
package com.basilv.examples.spring;
import java.util.Set;

public interface CalculatorService
{
  boolean validate(Resume resume);
}

public interface ResumeRepository
{
  Set&lt;Resume&gt; findAll();
}

public class Resume
{
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  private String name;
}
</pre>
<p>The implementation class of <code>CalculatorService</code> is <code>CalculatorServiceImpl</code> which requires (has a dependency on) <code>ResumeRepository</code>. The implementation class of <code>ResumeRepository</code> is <code>HardcodedResumeRepository</code>, which is used for this example rather than a more typical repository implementation to avoid further dependencies on e.g. a DataSource. These implementation classes are the same in terms of logic across the three approaches, but there are configuration differences so the code for these classes will be shown for each approach below.</p>
<h3>Explicit Declaration of Beans and Dependencies</h3>
<p>The explicit approach requires that all beans and their dependencies be explicitly coded within the configuration class as shown below:</p>
<pre class="prettyprint">
package com.basilv.examples.spring.explicit;

import org.springframework.config.java.annotation.*;
import com.basilv.examples.spring.*;

@Configuration
public class ExplicitConfig
{
  @Bean
  public ResumeRepository resumeRepository() {
    return new HardcodedResumeRepository();
  }

  @Bean
  public CalculatorService calculatorService() {
    return new CalculatorServiceImpl(
      resumeRepository()); // Inject dependency
  }
}
</pre>
<p>The <code>@Configuration</code> annotation is needed on the class, and each bean definition method must be annotated with <code>@Bean</code>. By default bean names are based on the method names.</p>
<p>The implementation classes <code>HardcodedResumeRepository</code> and <code>CalculatorServiceImpl</code> do not require any special configuration code. Constructor injection was used in <code>CalculatorServiceImpl</code> as it is safer and results in more compact code within the configuration class. The code for these implementation classes is shown below:</p>
<pre class="prettyprint">
package com.basilv.examples.spring.explicit;

import java.util.*;
import com.basilv.examples.spring.*;

public class HardcodedResumeRepository implements ResumeRepository
{
  public Set&lt;Resume&gt; findAll() {
    HashSet&lt;Resume&gt; set = new HashSet&lt;Resume&gt;();
    Resume resume = new Resume();
    resume.setName("Coded, Hard");
    set.add(resume);

    return set;
  }
}

public class CalculatorServiceImpl implements CalculatorService
{
  private ResumeRepository resumeRepository;

  public CalculatorServiceImpl(ResumeRepository resumeRepository) {
    this.resumeRepository = resumeRepository;
  }

  public boolean validate(Resume resume) {
      for (Resume repoResume : resumeRepository.findAll()) {
        if (repoResume.getName().equals(resume.getName())) {
          return true;
        }
      }

      return false;
  }
}
</pre>
<p>As explained above, using the <code>ExplicitConfig</code> configuration class is quite simple. The unit test shown below demonstrates how it is done.</p>
<pre class="prettyprint">
package com.basilv.examples.spring.explicit;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.Set;

import org.junit.*;
import org.springframework.config.java.context.JavaConfigApplicationContext;

import com.basilv.examples.spring.*;

public class ExplicitConfigTest
{
  private JavaConfigApplicationContext context;

  @Before
  public void setUp() {
    context = new JavaConfigApplicationContext(ExplicitConfig.class);
  }

  @Test
  public void repositoryConfig() {

    ResumeRepository resumeRepository = context.getBean(ResumeRepository.class);
    Set&lt;Resume&gt; resumes = resumeRepository.findAll();
    assertNotNull(resumes);
    assertTrue(!resumes.isEmpty());
  }

  @Test
  public void serviceConfig() {

    CalculatorService service = context.getBean(CalculatorService.class);
    assertNotNull(service);

    assertFalse(service.validate(new Resume()));
  }

}
</pre>
<p>One nice feature of the <code>JavaConfigApplicationContext</code> class is that beans can be retrieved  via the <code>getBean</code> method in a type-safe manner with no casting required. The only piece of this code that is specific to this approach is the configuration class used – the other approaches to defining dependencies do not need to change anything else in this test case.</p>
<p>At first glance it may appear that the configuration class with its explicit definitions could be used directly without Spring. That would be correct for this simplistic example. In real-life usage, however, the Spring Framework provides many additional features via its container including bean life-cycle events, bean scope (singleton versus prototype), and aspects such as transactional behavior.</p>
<h3>Automatic Dependencies via Autowiring</h3>
<p>While the explicit declaration approach described above may look quite reasonable for this simplistic example, in real-life usage the number of dependencies per class can really add up, particularly for Service classes that may require five or more Repository or other Service classes. Instead of manually defining all of these dependencies, Spring allows such dependencies to be inferred using a feature called Autowiring.</p>
<p>Here is how Autowiring works. Dependencies within an implementation class must be flagged with the <code>@Autowired</code> annotation. At bean construction time the Spring container will automatically populate these dependencies by finding a matching bean based on the Java type. (Multiple beans of the same type can be handled through the use of qualifiers or through the <code>@Resource</code> annotation. See the Spring documentation for further details.) </p>
<p>While the Spring XML-based configuration can autowire both constructor and setter injection, Java-based configuration cannot autowire dependencies in constructors when beans are explicitly defined. So for the example the <code>CalculatorServiceImpl</code> class had to be changed to use setter injection. Below is the code for the configuration class and <code>CalculatorServiceImpl</code> - the <code>HardcodedResumeRepository</code> class is unchanged from the explicit declaration approach.</p>
<pre class="prettyprint">
package com.basilv.examples.spring.autowire;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.config.java.annotation.*;
import org.springframework.config.java.plugin.context.AnnotationDrivenConfig;
import com.basilv.examples.spring.*;

@Configuration
@AnnotationDrivenConfig // Needed for @Autowire to work
public class AutowireConfig
{

  @Bean
  public ResumeRepository resumeRepository() {
    return new HardcodedResumeRepository();
  }

  @Bean
  public CalculatorService calculatorService() {
    return new CalculatorServiceImpl(); // Do not need to specify dependency.
  }
}

public class CalculatorServiceImpl implements CalculatorService
{
  @Autowired
  private ResumeRepository resumeRepository;

  public boolean validate(Resume resume) {
      for (Resume repoResume : resumeRepository.findAll()) {
        if (repoResume.getName().equals(resume.getName())) {
          return true;
        }
      }

      return false;
  }

  public void setResumeRepository(ResumeRepository resumeRepository) {
    this.resumeRepository = resumeRepository;
  }
}
</pre>
<h3>Automatic Beans via Component Scanning</h3>
<p>While the previous approach did reduce the amount of configuration required, each bean still needed to be explicitly defined within the configuration class. This approach eliminates this requirement by enabling Spring to scan for component classes that are automatically configured as beans with dependencies autowired as per the previous approach. Bean implementation classes must be annotated with the annotation <code>@Component</code> or a specialization of this annotation such as <code>@Service</code> or <code>@Repository</code>. The configuration class is then configured to scan one or more packages for these classes. The code below shows the configuration class and the two implementation classes which were revised to add these annotations. </p>
<pre class="prettyprint">
package com.basilv.examples.spring.componentscan;

import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.config.java.annotation.Configuration;
import org.springframework.config.java.plugin.context.*;
import org.springframework.stereotype.*;
import com.basilv.examples.spring.*;

@Configuration
@AnnotationDrivenConfig // Needed for @Autowire to work
@ComponentScan("com.basilv.examples.spring.componentscan")
public class ComponentScanConfig
{
  // No explicit configuration needed
}

@Repository
public class HardcodedResumeRepository implements ResumeRepository
{
  public Set&lt;Resume&gt; findAll() {
    HashSet&lt;Resume&gt; set = new HashSet&lt;Resume&gt;();
    Resume resume = new Resume();
    resume.setName("Coded, Hard");
    set.add(resume);

    return set;
  }
}

@Service
public class CalculatorServiceImpl implements CalculatorService
{
  private ResumeRepository resumeRepository;

  @Autowired
  public CalculatorServiceImpl(ResumeRepository resumeRepository) {
    super();
    this.resumeRepository = resumeRepository;
  }

  public boolean validate(Resume resume) {
      for (Resume repoResume : resumeRepository.findAll()) {
        if (repoResume.getName().equals(resume.getName())) {
          return true;
        }
      }

      return false;
  }
}
</pre>
<p>The most notable thing about this example is that the configuration class is empty – all bean definitions and dependencies have been inferred via annotations. The <code>CalculatorServiceImpl</code> class is also able to use autowired constructor injection, unlike the previous approach, because the class itself is being instantiated by the Spring container rather than explicitly in our configuration class.</p>
<h3>Pros and Cons</h3>
<p>There are advantages and disadvantages to each configuration approach. The explicit declaration approach is the easiest to understand, especially for developers unfamiliar with Spring. But this approach is the most work to set up. The approach of autowiring dependencies while explicitly defining beans strikes I believe a nice balance between these two factors. Implementation classes are still explicitly referenced, which I think is important for developers unfamiliar with Spring as otherwise IDEs will report no uses of such classes within the production code base. But all dependency information can be left out. A significant disadvantage with this approach, however, is that constructor injection cannot be autowired. In general I tend to prefer constructor injection, which makes this approach pointless (as constructor dependencies still need to be explicitly defined). The third approach of using component scanning is the most aggressive in minimizing configuration needed – virtually no setup work is required. But I am concerned that this will be much harder to understand for those developers unfamiliar with Spring as a lot of magic is being performed behind the scenes. </p>
<p>Is there a clear winner? I would say no, which is one reason Spring provides for these various configuration options. While I value the ease-of-understanding provided by the first approach, I strongly dislike writing "boilerplate" code, which much of the dependency configuration is, and this pushes me towards the third approach. As per the comment below from Chris Beams, Lead for the Spring JavaConfig project, his recommendation is to use component scanning and not use the hybrid explicit beans + autowiring approach. He also points out that 'external' dependencies, such as data sources, still require explicit configuration.</p>
<p>Despite the questions over the approach to defining dependencies, I am happy with the use of Spring JavaConfig overall. One issue I encountered using Spring JavaConfig is that it is still in beta – it has not had a final 1.0 release yet. I used JavaConfig 1.0.0.M4, which worked fine with Spring 2.5.6 but does not work with Spring 3.0.M2 due to classpath issues. I discovered on the Spring forums that some portion of the JavaConfig functionality with be included in the Spring 3.0 release due out this summer, but it is unclear what is planned for the remaining functionality. See Chris Beam's comment below for more details.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.basilv.com/psd/blog/2009/java-based-configuration-of-spring-dependency-injection/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

