<?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>etechGuide . . . &#187; dependency injection</title>
	<atom:link href="http://etechGuide.in/tag/dependency-injection/feed/" rel="self" type="application/rss+xml" />
	<link>http://etechGuide.in</link>
	<description>Know more , share more</description>
	<lastBuildDate>Fri, 25 Jun 2010 13:58:23 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Spring 3.0 &#8211; Java Annotation based Dependency Injection(DI)</title>
		<link>http://etechGuide.in/spring/spring3_annotation_di/</link>
		<comments>http://etechGuide.in/spring/spring3_annotation_di/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 11:51:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[dependency injection]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=553</guid>
		<description><![CDATA[<p>If you have been using Spring Framework for sometime , you will be aware that the Spring Framework has undergone several major changes in the latest Spring version 3.x. Spring Framework is now based on Java 5 and Java  6 fully supported. It has incorporated all the important features of Java latest versions. Spring version 3.0 encourages the developers to use Java Annotations instead of the configuration xml. This post will talk on the Annotation based <a href="http://etechguide.in/spring/dependency-injection-concept/">Dependency Injection</a> mechanism using Spring 3.0.</p>]]></description>
			<content:encoded><![CDATA[<p>If you have been using Spring Framework for sometime , you will be aware that the Spring Framework has undergone several major changes in the latest Spring version 3.x. Spring Framework is now based on Java 5 and Java  6 fully supported. It has incorporated all the important features of Java latest versions. Spring version 3.0 encourages the developers to use Java Annotations instead of the configuration xml. This post will talk on the Annotation based <a href="http://etechguide.in/spring/dependency-injection-concept/">Dependency Injection</a> mechanism using Spring 3.0.</p>
<p>In my one of the post I have discussed on setter injection using Spring 2.5(old method). Going through that <a href="http://etechguide.in/spring/setter-injection-type-of-dependency-injection/">post</a> will help you to find the difference between these two dependency injection approach. Lets get started.</p>
<p> <strong>What is Dependency Injection ?</strong> The answer is , It is a Design Pattern. Inversion of control or dependency injection pattern used to resolve component dependencies by injecting an instantiated component to satisfy dependency as opposed to explicitly requesting a component. So components will not be explicitly requested but components are provided as needed with the help of an Inversion of controller containers. Please read the <a href="http://etechguide.in/spring/dependency-injection-concept">post</a> to know more on it.</p>
<p> Spring has a concept of instantiated component , i.e , bean. Previously , we used to configure bean in the Application Context xml file but with Spring 3.0 , we will be configuring bean and injecting services(dependencies) from our java classes. Lets do it with an example use case.</p>
<p> Have a look at the following class relations </p>
<div id="class_relation" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Class Relation" src="http://etechGuide.in/wp-content/uploads/2010/01/Annotation_DI.PNG" alt="Class Relation" width="493" height="438" /><br />
<p class="wp-caption-text">Class Relation</p></div>
<p><strong>Use Case :</strong> OpsClient is a normal Java Class which is registered with two services , i.e , Calculator Service and Print Service. Calculator Service is an interface to different calculation services available , like , addition , multiplication etc. Print Service is another interface to different printing services available , like , printing to a file or printing to console etc. The OpsClient makes use of these different services to perform different calculation and print them on different printing interfaces.</p>
<p> <strong>Approach with Spring 3.0 :</strong>
<p> CalculatorService and PrintService are two interfaces. AddCalculatorServiceImpl , MultiplyCalculatorServiceImpl are the implementation of CalculatorService interface and ConsolePrintServiceImpl , FilePrintServiceImpl are the implementation of the PrintService interface. Hence , these implementation classes are the beans in Spring. Lets define them one by one. </p>
<h4><span style="text-decoration: underline;">Listing 1 : CalculatorService.java Interface</span></h4>
<pre class="brush: java">
package com.company.spring.basic.service;

public interface CalculatorService {

	public long calculate(long x,long y);
	public String getOperationName();

}
</pre>
<h4><span style="text-decoration: underline;">Listing 2 : PrintService.java Interface</span></h4>
<pre class="brush: java">
package com.company.spring.basic.service;

public interface PrintService {

	public void print(String result);
}
</pre>
<p> Lets define all the implementation (beans) of the services </p>
<h4><span style="text-decoration: underline;">Listing 3 : AddCalculatorServiceImpl.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.service.impl;

import javax.inject.Named;

import com.company.spring.basic.service.CalculatorService;
@Named(&quot;AddCalcService&quot;)
public class AddCalculatorServiceImpl implements CalculatorService {

	@Override
	public long calculate(long x, long y) {
		return x+y;
	}

	@Override
	public String getOperationName() {
		return &quot; plus &quot;;
	}
}
</pre>
<h4><span style="text-decoration: underline;">Listing 4 : MultiplyCalculatorServiceImpl.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.service.impl;

import javax.inject.Named;

import com.company.spring.basic.service.CalculatorService;
@Named(&quot;MultiplyCalcService&quot;)
public class MultiplyCalculatorServiceImpl implements CalculatorService {

	@Override
	public long calculate(long x, long y) {

		return x*y;
	}

	@Override
	public String getOperationName() {

		return &quot; multiplies &quot;;
	}
}
</pre>
<h4><span style="text-decoration: underline;">Listing 5 : ConsolePrintServiceImpl.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.service.impl;

import javax.inject.Named;

import com.company.spring.basic.service.PrintService;
@Named(&quot;ConsolePrintService&quot;)
public class ConsolePrintServiceImpl implements PrintService {

	@Override
	public void print(String result) {
		System.out.println(result);

	}
}
</pre>
<h4><span style="text-decoration: underline;">Listing 6 : ConsolePrintServiceImpl.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.service.impl;

import javax.inject.Named;

import com.company.spring.basic.service.PrintService;

@Named(&quot;FilePrintService&quot;)
public class FilePrintServiceImpl implements PrintService{

	@Override
	public void print(String result) {
          // Code to write to a file
	}
}
</pre>
<p>Listing 3 &#8211; Listing 6 shows the normal but special implementation of the interfaces. They are special , because they are to support the Spring Framework&#8217;s Bean concept. To do that , each of this implementation is annotated with @Named(&#8221;SomeName&#8221;) annotation. In Spring 3.x you can use JSR 330&#8217;s @Named annotation in place of stereotype annotations and they will be automatically detected during component-scanning.<br />
The value of the @Named property will be used as the Bean Name. At this time Spring defaults for bean<br />
scope will be applied when using @Named.</p>
<p> This annotation will be available if if the JSR330 jar is present on the classpath. This jar is not part of the Spring 3.0 download. It is available under SpringSource Enterprise Bundle Repository. This annotation will be available under the <a href="http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.javax.inject&#038;version=1.0.0">com.springsource.javax.inject-1.0.0.jar</a>. You can find the other jars <a href="http://www.springsource.com/repository/app/bundle">here</a>.</p>
<p>The next task is to build the Application context. Wait , we are not going to build any xml file here. It is going to be a simple Java class annotated with some useful annotations. Have a look at the following code.</p>
<h4><span style="text-decoration: underline;">Listing 7 : ApplicationConfig.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.company.spring.basic.client.OpsClient;
import com.company.spring.basic.service.CalculatorService;
import com.company.spring.basic.service.PrintService;
import com.company.spring.basic.service.impl.AddCalculatorServiceImpl;
import com.company.spring.basic.service.impl.ConsolePrintServiceImpl;
import com.company.spring.basic.service.impl.FilePrintServiceImpl;
import com.company.spring.basic.service.impl.MultiplyCalculatorServiceImpl;

@Configuration
public class ApplicationConfig {
	@Bean
	public PrintService screnPrint(){
		return new ConsolePrintServiceImpl();
	}
	@Bean
	public PrintService filePrint(){
		return new FilePrintServiceImpl();
	}
	@Bean
	public CalculatorService add(){
		return new AddCalculatorServiceImpl();
	}
	@Bean
	public CalculatorService Multiply(){
		return new MultiplyCalculatorServiceImpl();
	}
	@Bean
	public OpsClient result(){
		return new OpsClient();
	}
}
</pre>
<p> The class is annotated with @Configuration annotation. Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. These classes(@ Configuration annotated) consist principally of @Bean-annotated methods that define instantiation,configuration, and initialization logic for objects to be managed by the Spring IoC container.</p>
<p> To declare the beans , we have created methods and annotated with the @Bean annotation. The @Bean annotation plays the same role as the <bean/> element.When @Configuration classes are provided as input, the @Configuration class itself is registered as a bean definition, and all declared @Bean methods within the class are also registered as bean definitions.</P></p>
<p> So we have five beans declared all together. The last bean declared is the OpsClient bean which has two references , i.e , CalculatorService and PrintService(Please refer to the Class Relations diagram above). We will achieve this reference injection with the help of a very special annotation @Inject. Have a look.</p>
<h4><span style="text-decoration: underline;">Listing 8 : OpsClient.java </span></h4>
<pre class="brush: java">
package com.company.spring.basic.client;

import javax.inject.Inject;
import javax.inject.Named;
import com.company.spring.basic.service.CalculatorService;
import com.company.spring.basic.service.PrintService;

public class OpsClient {

	@Inject
	@Named(&quot;FilePrintService&quot;)
	private PrintService printService;

	@Inject
	@Named(&quot;MultiplyCalcService&quot;)
	private CalculatorService calculatorService;

	public void execute(long op1,long op2)  {
		printService.print(&quot;The result of &quot; + op1 +
				calculatorService.getOperationName() + op2 + &quot; is &quot;
	   			+ calculatorService.calculate(op1, op2) + &quot;!&quot;);

	}
}
</pre>
<p> printService and the calculatorCulatorService are the references to the different service implementations which can be injected using the @Inject annotation and @Named annotations. Here @Named annotation work as a mapping of service implementations. The name supplied as a parameter to the @Named annotation should be matched with one of the service implementation annotated with the same @Named annotation.</p>
<p> Like @Named , @Inject annotation can be found under the same package javax.inject.Inject. In the above class we are injecting the multiplication calculator service and the file print service using the annotations. Now the only thing pending is to instantiate the Application Context and call the client. It is explained below ,</p>
<h4><span style="text-decoration: underline;">Listing 9 : OperationTest.java </span></h4>
<pre class="brush: java">
public class OperationTest {
	public static void main(String[] args) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(
				com.company.spring.basic.ApplicationConfig.class);
		OpsClient opsBean = ctx.getBean(OpsClient.class);
		opsBean.execute(2, 3);
	}
}
</pre>
<p> Once you run the above method , multiplication of the value 2 and 3 will be written in a file.</p>
<p> You would need to add the following jar files to the class-path ,<br />
- cglib-nodep-2.1_3.jar<br />
- classworlds-1.1-alpha-2.jar<br />
- com.springsource.javax.inject-1.0.0.jar<br />
- com.springsource.javax.inject-sources-1.0.0.jar<br />
- jcl-over-slf4j-1.5.10.jar<br />
- log4j-1.2.15.jar<br />
- slf4j-api-1.5.10.jar<br />
- slf4j-log4j12-1.5.10.jar<br />
- spring-aop-3.0.0.RELEASE.jar<br />
- spring-asm-3.0.0.RELEASE.jar<br />
- spring-beans-3.0.0.RELEASE.jar<br />
- spring-context-3.0.0.RELEASE.jar<br />
- spring-core-3.0.0.RELEASE.jar<br />
- spring-expression-3.0.0.RELEASE.jar<br />
- spring-jdbc-3.0.0.RELEASE.jar<br />
- spring-tx-3.0.0.RELEASE.jar</p>
<p>Most of the above jars can be downloaded as part of Spring 3.x download. Other jars can be found <a href="http://www.springsource.com/repository/app/bundle">here</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fspring3_annotation_di%2F&amp;linkname=Spring%203.0%20%26%238211%3B%20Java%20Annotation%20based%20Dependency%20Injection%28DI%29"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/spring/spring3_annotation_di/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Setter Injection &#8211; Type of Dependency Injection</title>
		<link>http://etechGuide.in/spring/setter-injection-type-of-dependency-injection/</link>
		<comments>http://etechGuide.in/spring/setter-injection-type-of-dependency-injection/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 05:25:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[setter injection]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=478</guid>
		<description><![CDATA[<p>I have discussed on the concept of Dependency Injection in my <a href="http://etechguide.in/spring/dependency-injection-concept/">last post</a> . This post is about a specific type of Dependency Injection adopted by Spring. It is called <strong>Setter Injection</strong>. In Java POJO(Plain old java object) world , setters and getters are very common terms. A setter which sets an attribute value of a class. A getter which return the attribute value of a class.</p>]]></description>
			<content:encoded><![CDATA[<p>I have discussed on the concept of Dependency Injection in my <a href="http://etechguide.in/spring/dependency-injection-concept/">last post</a> . This post is about a specific type of Dependency Injection adopted by Spring. It is called <strong>Setter Injection</strong>. In Java POJO(Plain old java object) world , setters and getters are very common terms. A setter which sets an attribute value of a class. A getter which return the attribute value of a class.</p>
<p>Dependency can be injected using the setter method of a class. If a class is dependent on another class or primitive variables then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. </p>
<p>For an example , lets say Employee class is dependent on Address class , Employee class should have a state variable and a setter method , like , </p>
<h4><u>Listing 1 : Class with a setter method</u></h4>
<pre class="brush: java">
private Address address;
public void setAddress(Address address) {
        this.address = address;
}
</pre>
<p>The Spring IOC container should inject the address dependency using the setter method of Address. Whole dependency Injection is push method where a dependency value will be pushed and a client class should not bother about pulling the dependency back from anywhere. Lets learn to set setter dependency injection with following example.</p>
<p>Lets assume , we have a class relation like the following ,</p>
<h4><u>Listing 2 : Class Relations</u></h4>
<div id="class_relation" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Employee has an Address and a Project" src="http://etechGuide.in/wp-content/uploads/2009/12/StterInjectionClassRelations.PNG" alt="Employee has an Address and a Project" width="350" height="350" /><br />
<p class="wp-caption-text">Employee has an Address and a Project</p></div>
<p>Look at the above class relations. Employee has an Address and Employee has a Project. Employee is dependent on both Address and Project classes directly. Using Spring IOC controller we can inject the dependency values to Employee class . Lets do it.</p>
<p>Spring IOC container needs a bean to be defined for all kind of classes whose object should be created for your application. For the above application we need instance of an Address class , Project Class and at last Employee class to get the employee data. Hence we need three beans to be declared. Beans should be declared in the application context xml file. The
<pre class="brush: xml"> &lt;bean&gt; </pre>
<p>tag should define a bean with it&#8217;s properties and <beans> tag should contain multiple beans in it.</p>
<p>Address class has three properties , i.e , street , city and pincode. Hence the bean for the Address class is defined as follows ,</p>
<h4><u>Listing 3 : Address Bean</u></h4>
<pre class="brush: xml">
&lt;bean id=&quot;addressBean&quot;
class=&quot;com.company.spring.injection.setter.model.Address&quot;&gt;
        &lt;property name=&quot;street&quot;&gt;
            &lt;value&gt;Bagmane Tech park&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;city&quot;&gt;
            &lt;value&gt;Bangalore&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;pincode&quot;&gt;
            &lt;value&gt;566093&lt;/value&gt;
        &lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>Intention is to instantiate the Address class and populate it&#8217;s properties with respective values. Similar way , a bean definition for Project class could be as,</p>
<h4><u>Listing 4 : Project Bean</u></h4>
<pre class="brush: xml">
&lt;bean id=&quot;projectBean&quot;
class=&quot;com.company.spring.injection.setter.model.Project&quot;&gt;
        &lt;property name=&quot;projectName&quot;&gt;
            &lt;value&gt;iManager&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;department&quot;&gt;
            &lt;value&gt;ISM&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;teamMemberCount&quot;&gt;
            &lt;value&gt;10&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;deliveryDate&quot;&gt;
            &lt;ref bean=&quot;dateBean&quot;/&gt;
        &lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>Point to notice is that the bean id is a logical name which can be any user friendly and non-objectionable <img src='http://etechGuide.in/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  name. Look at these bean definition closely. Each bean has property and each property is populated with some value. But thing is different for deliveryDate bean in projectBean. There is a
<pre class="brush: xml">&lt;ref&gt;</pre>
<p> tag instead of
<pre class="brush: xml">&lt;value&gt;</pre>
<p>. Because deliveryDate property is of type java.util.Date in Project class so we need a java.util.Date reference to set it&#8217;s value. So we need another bean for date. </p>
<h4><u>Listing 5 : Date Bean</u></h4>
<pre class="brush: xml">
&lt;bean id=&quot;dateBean&quot;
class=&quot;java.util.Date&quot;/&gt;
</pre>
<p>Now , lets have a look at the bean for the Employee class.</p>
<h4><u>Listing 6 : Employee Bean</u></h4>
<pre class="brush: xml">
&lt;bean id=&quot;employeeBean&quot;
class=&quot;com.company.spring.injection.setter.model.Employee&quot;&gt;
        &lt;property name=&quot;name&quot; value=&quot;Tapas Adhikary&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;empId&quot; value=&quot;88699&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;address&quot; ref=&quot;addressBean&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;project&quot; ref=&quot;projectBean&quot;&gt;&lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>See the last two properties of the employeeBean bean. We have injected the addressBean and projectBean as a reference to the properties names address and project respectively. So your client code ( Where we have decided to create and instance of Employee and call it&#8217;s getter methods) should not worry about setting all this values. Employee&#8217;s dependencies will be pushed by the Spring IOC container.</p>
<p>The client code should be like this ,</p>
<h4><u>Listing 7 : Setter Injection Java file</u></h4>
<pre class="brush: java">
public class SetterInjection {
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext(
          &quot;resources/applicationContext.xml&quot;);
    BeanFactory factory = (BeanFactory) context;
    Employee employee = (Employee) factory.getBean(&quot;employeeBean&quot;);
    Address address = employee.getAddress();
    Project project = employee.getProject();
    System.out.println(employee.getName());
    System.out.println(employee.getEmpId());
    System.out.println(address.getCity());
    System.out.println(address.getStreet());
    System.out.println(address.getPincode());
    System.out.println(project.getProjectName());
    System.out.println(project.getDepartment());
    System.out.println(project.getTeamMemberCount());
    System.out.println(project.getDeliveryDate().toString());
   }
}
</pre>
<p>Lets assume the application context file name is applicationContext.xml and it&#8217;s under a folder called resources. An ApplicationContext object should be formed with the help of the xml file. The context object is type of the Bean Factory which uses the Factory Design Pattern concept to create the object. Once you get the factory , you need to query the bean using the bean name , i.e , employeeBean. Thats it. Your Employee class is instantiated. Now you can get all the Employee properties including Address and Project properties injected using the xml file and the setter method of Address , Person and Employee.</p>
<p>The attached source code has the full version of the xml and all java source files. Download the code and import into your favorite IDE.</p>
<p>              I would like to conclude this post with one rule. A property name of a bean in the xml file should be equal to the setter method name of the attribute of the class without the word set at the beginning . Say if the property name of a bean in the application context xml file is departmentName then the corresponding class should have a setter method called </P></p>
<pre class="brush: java">
 public void setDepartmentName(String departMent){
     // Set the value
   }
</pre>
<p>
Note : &#8216;D&#8217; is in capital in the setter method after the word &#8217;set&#8217;.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fsetter-injection-type-of-dependency-injection%2F&amp;linkname=Setter%20Injection%20%26%238211%3B%20Type%20of%20Dependency%20Injection"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/spring/setter-injection-type-of-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
