<?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; Spring</title>
	<atom:link href="http://etechGuide.in/tag/spring/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>Spring DAO &#8211; JDBC Support</title>
		<link>http://etechGuide.in/spring/spring-dao-jdbc-support/</link>
		<comments>http://etechGuide.in/spring/spring-dao-jdbc-support/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 11:05:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[dao]]></category>
		<category><![CDATA[jdbc]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=506</guid>
		<description><![CDATA[Spring framework has a full-fledge support for the Database Access Objects(DAO). Spring’s support of DAO is not limited with the relational database like MySQL , Oracle , etc . It has support for Object Relational Databases like , HSQL , JDO etc. Whan I talk about suppot it means a lot of things.

Before going into the details , let us ask a question to ourselves .What is the real problem in coding a JDBC without a framework support ?]]></description>
			<content:encoded><![CDATA[<h4><span style="text-decoration: underline;">Introduction</span></h4>
<p>Spring framework has a full-fledge support for the Database Access Objects(DAO). Spring&#8217;s support of DAO is not limited with the relational database like MySQL , Oracle , etc . It has support for Object Relational Databases like , HSQL , JDO etc. Whan I talk about suppot it means a lot of things.</p>
<p>Before going into the details , let us ask a question to ourselves .What is the real problem in coding a JDBC without a framework support ?</p>
<p>All of us , who are JDBC programmers know these clearly :</p>
<ul>
<li>DBC is redundant .</li>
<li>Lots of Coding to be done .</li>
<li>Lots of Coding to be repeated (Yes , even after following all the OO academic theories !!).</li>
<li>Extra headache of Opening a connection and Closing a connection .</li>
<li>Maintaining a Connection Pool .</li>
<li>You find yourself doing the same things over and over again .</li>
<li>Yes , you must have to propagate the exception and handle it .</li>
<li>You have to handle transactions .</li>
<li>You have to write statements .</li>
<li>You have to execute the statements .</li>
<li>You have to get the results after executing the statement and iterate through it.</li>
</ul>
<p><span>Waoh !! So many things to take care. Isn&#8217;t it ?</span><span> What do the framework like Spring do then ? How does it help ?<br />
Here is the list of what it does (We will see the <em>HOW</em> shortly) :</span></p>
<ul>
<li>Define connection parameters .</li>
<li>Open the connection .</li>
<li><span><em>Specify the statement . &#8211; Work of an Application Developer.<br />
</em></span></li>
<li><span><em> </em></span>Prepare and execute the statement .</li>
<li>Set up the loop to iterate through the results (if any) .</li>
<li><span><em>Do the work for each iteration . </em></span><span><em>- Work of an Application Developer.</em></span></li>
<li><span><em> </em></span>Process any exception .</li>
<li>Handle transactions .</li>
<li>Close the connection .</li>
</ul>
<p>In the above list , Except specifying the statement and writing the business logic for each iteration , all other services are taken care by the SPRING Framework. Isn&#8217;t it cool ? You don&#8217;t have to worry about many things that would have taken most of your development time otherwise.</p>
<h4><span style="text-decoration: underline;">Know the Spring DAO Module :</span></h4>
<p><span style="text-decoration: underline;">Packages</span></p>
<p>The Spring Framework&#8217;s JDBC abstraction framework consists of four different packages, namely core, datasource, object, and support. Spring community documentation helps you with number of options for selecting an approach to form the basis for your JDBC database access.</p>
<ul>
<li><span><strong>JdbcTemplate</strong></span> &#8211; this is the classic Spring JDBC approach and the most widely used. Works well in a JDK 1.4 and higher environment.</li>
<li><span><strong>NamedParameterJdbcTemplate</strong></span> &#8211; wraps a JdbcTemplate to provide more convenient usage with named parameters instead of the traditional JDBC &#8220;?&#8221; place holders. This provides better documentation and ease of use when you have multiple parameters for an SQL statement. Works with JDK 1.4 and up.</li>
</ul>
<ul>
<li>
<span><strong>SimpleJdbcTemplate</strong></span> &#8211; this class combines the most frequently used features of both JdbcTemplate and NamedParameterJdbcTemplate plus it adds additional convenience by taking advantage of some Java 5 features like varargs, autoboxing and generics to provide an easier to use API. Requires JDK 5 or higher.
</li>
<li>
<span><strong>SimpleJdbcInsert and SimpleJdbcCall</strong></span> &#8211; designed to take advantage of database metadata to limit the amount of configuration needed. This will simplify the coding to a point where you only need to provide the name of the table or procedure and provide a Map of parameters matching the column names. Designed to work together with the SimpleJdbcTemplate. Requires JDK 5 or higher and a database that provides adequate metadata.
</li>
<li>
<span><strong>RDBMS Objects including MappingSqlQuery, SqlUpdate and StoredProcedure</strong></span> &#8211; an approach where you create reusable and thread safe objects during initialization of your data access layer. This approach is modeled after JDO Query where you define your query string, declare parameters and compile the query. Once that is done any execute methods can be called multiple times with various parameter values passed in. Works with JDK 1.4 and higher.
</li>
</ul>
<p>Lets see one example to learn and understand Spring-jdbc configuration. We will use jdbcTemplate style of JDBC approach. Reader of this post is expected to try other approaches as well.</p>
<p><span style="text-decoration: underline;">Setup Details</span></p>
<p>DataBase used : MySQL 5<br />
IDE Used : Eclipse 3.3.1<br />
Jar files needed : Please inclusde the followings jar into project classpath.</p>
<ol>
<li>commons-dbcp.jar &#8211; For DataSource Support.</li>
<li>commons-pool.jar &#8211; For Connection Pool Support.</li>
<li>mysql-connector-java-5.1.5.jar &#8211; Java Connector for MYSQL.</li>
<li>ojdbc14.jar &#8211; Query Support</li>
<li>spring.jar &#8211; The core framework library</li>
</ol>
<p>All the above jar files should be found under lib/ and dist/ directory of the Spring Distribution with Dependencies.</p>
<p>Lsts take an example of a table called User which is created under the data base called demo. The description of the demo.User table is as follows,</p>
<div id="command" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="describe table" src="http://etechGuide.in/wp-content/uploads/2009/12/User_DB_desc.PNG" alt="describe table" title="describe table" width="550" height="71" /><br />
<p class="wp-caption-text">describe table</p></div>
<p>Let us create a domain class called User which is a POJO(Plain old java object) class having the properties and setter / getters for the properties. A User.java look like ,</p>
<h4><span style="text-decoration: underline;">Listing 1 : User.java</span></h4>
<pre class="brush: java">
public class User {

          private Integer uid;
          private String userName;
          private String password;

          public User() {

          }
          public User(Integer uid, String userName, String password) {
                  this.uid = uid;
                  this.userName = userName;
                  this.password = password;
          }
          public Integer getUid() {
                  return uid;
          }
          public void setUid(Integer uid) {
              this.uid = uid;
          }
          public String getUserName() {
             return userName;
          }
          public void setUserName(String userName) {
            this.userName = userName;
          }
          public String getPassword() {
              return password;
          }
          public void setPassword(String password) {
                   this.password = password;
          }

         public String toString(){
              StringBuilder sb = new StringBuilder();
              sb.append(&quot;User ID :&quot;+getUid()+&quot;\n&quot;);
              sb.append(&quot;User Name :&quot;+getUserName());
              return sb.toString();
         }

    }
</pre>
<p>As the design pattern teaches us, we should do all the programming to interfaces and not to implementation . let us create an interface called UserDAO which will declare all the methods to be implemented for a User database operation.</p>
<h4><span style="text-decoration: underline;">Listing 2 : UserDAO.java</span></h4>
<pre class="brush: java">
public interface UserDAO {
    public boolean insertUser(User userRecord);
    public boolean updateUser(User userRecord);
    public boolean deleteUser(int uid);
    public User selectUser(int uid);
}
</pre>
<p>Before going to the implementation of UserDAO interface , we should know the following :<br />
      &#8211; Spring Framework will provide a mechanism to inject TransactionManager and DataSource instance to our implementation class.<br />
      &#8211; A Datasource can contain information like, driverClassName,url,username,password etc and all this information (parameters) will be injected by container to the implementation class.<br />
We will achieve these by coding our ApplicationContext.xml . Here it is .</p>
<h4><span style="text-decoration: underline;">Listing 3 : ApplicationContext.xml</span></h4>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot;&gt;

    &lt;bean id=&quot;dataSource&quot;
         class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;
           destroy-method=&quot;close&quot;&gt;
        &lt;property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;
        &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/demo&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;root&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;abcdef&quot;/&gt;
        &lt;property name=&quot;maxActive&quot; value=&quot;10&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;maxIdle&quot; value=&quot;5&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;minIdle&quot; value=&quot;1&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;poolPreparedStatements&quot; value=&quot;true&quot;&gt;&lt;/property&gt;
        &lt;property name=&quot;initialSize&quot; value=&quot;1&quot;&gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;transactionManager&quot;
class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot;&gt;
 &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;&gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;userDao&quot; class=&quot;user.DAO.Impl.UserDaoImpl&quot;&gt;
   &lt;property name=&quot;transactionManager&quot;ref=&quot;transactionManager&quot;&gt;&lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>Look at the last bean , userDao. This bean instantiate UserDaoImpl which is an implementation os UserDAO interface. As per the setter injection logic , UserDaoImpl.java should have a setter method for the reference property transactionManager. Now , have a look at the transactionManager bean. This is a type of (say , instance of) class org.springframework.jdbc.datasource.DataSourceTransactionManager . This is a class provided by the Spring Framework to the application developer. This class has a public setDataSource(DataSource dataSource) method. Hence you have the scope to inject dataSource object as a refrence to the transactionManager bean. </p>
<p>The dataSource bean is of type org.apache.commons.dbcp.BasicDataSource which has setter for all the properties defined under the bean. Additionaly , the bean described theat close() method will be called as a destroy-method to close the connection.</p>
<p>The Sequence is like this ,<br />
- Get a TransactionManager instance,<br />
- Get a DataSource from TransactionManager.<br />
- Form a jdbcTemplate from the Datasource instance.<br />
- Specify the Query.</p>
<p>All the above steps are taken care in the UserDaoImpl.java class. Have a look.</p>
<h4><span style="text-decoration: underline;">Listing 4 : UserDaoImpl.java</span></h4>
<pre class="brush: java">

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import user.DAO.UserDao;
import user.Domain.User;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    // Setter Injection happens here
    public void setTransactionManager(
            DataSourceTransactionManager transactionManager) {
        DataSource dataSource= transactionManager.getDataSource();
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public boolean deleteUser(int uid) {
        String sql = &quot;delete from demo.user where UID=?&quot;;
        Object[] params = new Object[]{uid};
        int deleted = jdbcTemplate.update(sql,params);
        if(deleted &gt; 0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean insertUser(User userRecord) {

		String sql = &quot;insert into demo.user(UID,USERNAME,PASSWORD)&quot;
				+ &quot; values(?,?,?)&quot;;
		Object[] params = new Object[] { userRecord.getUid(),
				userRecord.getUserName(), userRecord.getPassword() };
		int[] types = new int[] { Types.INTEGER, Types.VARCHAR,
                            Types.VARCHAR };
		int inserted = jdbcTemplate.update(sql, params, types);
		if (inserted &gt; 0)
			return true;
		else
			return false;
    }

    @Override
    public User selectUser(int uid) {
        String sql = &quot;select UID,USERNAME from demo.user where UID=?&quot;;
        Object[] params = new Object[]{uid};
        final User user = new User();

        jdbcTemplate.query(sql,params,new RowCallbackHandler(){

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                user.setUid(new Integer(rs.getInt(&quot;UID&quot;)));
                user.setUserName(rs.getString(&quot;USERNAME&quot;));
            }
        });
        return user;
    }

    @Override
    public boolean updateUser(User userRecord) {
        // You Implement
        return false;
    }

}
</pre>
<p>
Inspect the public void setTransactionManager(DataSourceTransactionManager transactionManager) method . The Dependency Injection takes place here. TransactionManager instance will be injected by Spring IOC container using the setter injection methodology. Once the TransactionManager is populated , a datasource instance can be created as ,<br />
DataSource dataSource= transactionManager.getDataSource();<br />
and a jdbcTemplate can be created as,<br />
jdbcTemplate = new JdbcTemplate(dataSource);
</p>
<p>
This jdbcTemplate should be used for all type of query execution. To understand different types of query execution , please refer to the <a href="http://static.springsource.org/spring/docs/2.5.x/reference/jdbc.html">Spring Source Doc on JDO</a> (from section 11.2) after running the above program successfully.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fspring-dao-jdbc-support%2F&amp;linkname=Spring%20DAO%20%26%238211%3B%20JDBC%20Support"><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/spring-dao-jdbc-support/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrate any J2EE-based web application with Spring</title>
		<link>http://etechGuide.in/spring/integrate-any-j2ee-based-web-application-with-spring/</link>
		<comments>http://etechGuide.in/spring/integrate-any-j2ee-based-web-application-with-spring/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 09:53:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[jdbc]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=493</guid>
		<description><![CDATA[Spring is a very good modular framework. Each module of the framework can be used depending on the various need in an application. Lets take an example of a J2EE-based web application which can use Spring-DAO module for it's data base layer or Spring-MVC to make the navigation between Model-View-Controller more modular and testable.
But , there might be a situation where Spring-MVC is not your need , rather you would like to take advantage of Spring-DAO module along with normal servlets and jsps. What to do then ?]]></description>
			<content:encoded><![CDATA[<p>Spring is a very good modular framework. Each module of the framework can be used depending on the various need in an application. Lets take an example of a J2EE-based web application which can use Spring-DAO module for it&#8217;s data base layer or Spring-MVC to make the navigation between Model-View-Controller more modular and testable.</p>
<p>These factors decides which component of the Spring can be used with the J2EE-based web application. If you are using Spring-MVC for your web application , Spring provides a front-controller in form of DispatcherServlet which does loading of of application context , instantiating your beans etc.</p>
<p>But , there might be a situation where Spring-MVC is not your need , rather you would like to take advantage of Spring-DAO module along with normal servlets and jsps. In this scenario , DispatchServlet(the front-controller) is not at all there in picture. But the challenge remain the same. Your application context must be loaded and all the beans should be instantiated.</p>
<p>This post talks on integrating the Spring framework with a J2EE-based web application which has normal servlets and jsps.</p>
<p>Two areas of your web application should be modified to integrate with Spring framework.</p>
<ul>
<li><strong>web.xml file</strong> &#8211; Where you need to specify the path of the Spring&#8217;s application context file and register some listeners.</li>
<li><strong>Your servlet</strong> &#8211; where you need make changes to get the instance of your bean to call bean&#8217;s methods.</li>
</ul>
<p>Lets assume , we have an application context which declares the beans for configuring and connecting to the Database. The application context file will look like this ,</p>
<h4><u>Listing 1 : Application Context Xml &#8211; databaseAppConfig.xml</u></h4>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot;&gt;

	&lt;bean id=&quot;dataSource&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;&gt;
        &lt;property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;
        &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/library&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;root&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;novell&quot;/&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;jdbcTemplate&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;
		&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;&gt;&lt;/property&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;bookDao&quot; class=&quot;com.etechguide.library.client.dao.BookDaoImpl&quot;&gt;
		&lt;property name=&quot;jdbcTemplate&quot; ref=&quot;jdbcTemplate&quot;&gt;&lt;/property&gt;
	&lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>Next , add these tags to the top of web.xml</p>
<p>A context-param tag with the param-name contextConfigLocation and it&#8217;s value. contextConfigLocation is the location of Spring&#8217;s application context file. you can define multiple application context files and declare them in space separated manner.</p>
<pre class="brush: xml">
&lt;!-- context-param --&gt;
&lt;context-param&gt;
   &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
   &lt;param-value&gt;/WEB-INF/databaseAppConfig.xml&lt;/param-value&gt;
&lt;/context-param&gt;
</pre>
<p>A listener which would load all these context files and pass it to Spring framework for instantiating the beans defined in the application conext xml file.</p>
<pre class="brush: xml">
&lt;!-- listener --&gt;
  &lt;listener&gt;
    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener
  &lt;/listener-class&gt;
&lt;/listener&gt;
</pre>
<p>Once you are done with this step , use your servlet to get the instance of the bean created for you. If you look closely to the databaseAppConfig.xml file in the Listing 1 , you have a bean named <em>bookDao</em> which is the bean for the class file , com.etechguide.library.client.dao.BookDaoImpl. Lets assume , BookDaoImpl implements the interface BookDao.java and has definition of the methods like getBookDetails(), updateBook() deleteBook() etc. Hence you have to get the instance of BookDaoImpl if you would like to call the methods.</p>
<p> Have look at the following code , </p>
<pre class="brush: java">

public class BookDetailsSrvlet extends
      javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {

	private ServletConfig servletConfig = null;
	private ServletContext servletContext = null;
	private String state = null;
	private BookDao bookDao = null;

	protected ApplicationContext applicationContext;

	@Override
	public void init(ServletConfig config) throws ServletException {

		super.init(config);
		this.servletConfig = config;
		servletContext = this.servletConfig.getServletContext();
		if (applicationContext == null) {
			applicationContext = WebApplicationContextUtils
					.getWebApplicationContext(servletContext);
		}
		bookDao = (BookDao) applicationContext.getBean(&quot;bookDao&quot;);
	}
 .....
 .....
 // Other codes
 .....
 .....
}
</pre>
<p>The above code is from a servlet which makes use of the servletContext to get the ApplicationContext object and then called the getBean() method passing the bean name to get the instance of BookDaoImpl which is a type of BookDao interface.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fspring%2Fintegrate-any-j2ee-based-web-application-with-spring%2F&amp;linkname=Integrate%20any%20J2EE-based%20web%20application%20with%20Spring"><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/integrate-any-j2ee-based-web-application-with-spring/feed/</wfw:commentRss>
		<slash:comments>0</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>
		<item>
		<title>Dependency Injection Concept</title>
		<link>http://etechGuide.in/spring/dependency-injection-concept/</link>
		<comments>http://etechGuide.in/spring/dependency-injection-concept/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 05:38:49 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[ioc]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=462</guid>
		<description><![CDATA[<p>Java classes and objects should be as much as possible loosely coupled with other java classes and objects. The loosely-coupled behavior allows a Java code to be re-usable ,test-worthy , modular and well maintained. Often , A class depends on another class and arise the coupling .</p>
<p> Dependency Injection(DI) mechanism helps to introduce the loose coupling which makes your code more modular and testable.</p>
<p> The container which supports this dependency injection concept is called the I<strong>OC (Inversion of control) Container</strong>. Spring uses the concept of IOC and dependency injection to locate and inject services for you. </p>
<p> Read more to know more </p>
]]></description>
			<content:encoded><![CDATA[<p>Java classes and objects should be as much as possible loosely coupled with other java classes and objects. The loosely-coupled behavior allows a Java code to be re-usable ,test-worthy , modular and well maintained. Often , A class depends on another class and arise the coupling .</p>
<p>Say a class <em>FetchUserDataFromDB</em> depends on a class called <em>DataBaseAccess</em>, so it is obvious that , one would try to make a coupling by creating an instance of DataBaseAccess class in FetchUserDataFromDB class and call it&#8217;s methods. Here , we introduce a tight coupling and a strong dependency.</p>
<p>Look at the following scenarios :</p>
<h4><strong><span style="text-decoration: underline;">Scenario 1 : Tight Coupling</span> </strong></h4>
<div id="tight_coupling" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Tight Coupling" src="http://etechGuide.in/wp-content/uploads/2009/11/tight_couple_DI.PNG" alt="Tight Coupling" width="289" height="299" /><br />
<p class="wp-caption-text">Tight Coupling</p></div>
<p><strong>Step 1 :</strong> Get me a database connection object from the pool.<br />
<strong>Step 2 :</strong> Take the database connection object conn.<br />
<strong>Step 3 :</strong> Thanks you , get me the User&#8217;s data whose id is 007.<br />
<strong>Step 4 :</strong> Here it is , His name is James Bond .<br />
<strong>Step 5 :</strong> Enough , Don&#8217;t want the conn anymore. Close it.<br />
<strong>Step 6 :</strong> Ok , closed and conn is taken back to pool.</p>
<h4><strong><span style="text-decoration: underline;">Scenario 2 : Loose Coupling</span> </strong></h4>
<div id="loose_coupling" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Loose Coupling" src="http://etechGuide.in/wp-content/uploads/2009/11/loose_couple_DI.PNG" alt="Loose Coupling" width="304" height="285" /><br />
<p class="wp-caption-text">Loose Coupling</p></div>
<p><strong>Step 1 :</strong> Oh , you need a connection ? Injecting a connection conn from the Connection Pool.<br />
<strong>Step 2 :</strong> Fine , you need the user&#8217;s Information whose id is 007 ? Injecting the information ; He is James Bond.<br />
<strong>Step 3 :</strong> Look like you are not using the conn anymore. Injecting a service to close the connection and get the conn back to the pool.</p>
<p>Now the million dollar question is , which of these scenarios you would like to see in your code/project. Undoubtedly the scenario 2 where you do not have the burden of keeping a reference to the databaseaccess object and your client class is no more tightly coupled .<br />
Scenario 2 is the depiction of the Dependency Injection. Where the container injects the dependencies to the client classes and takes care of a full life cycle.</p>
<p>There are several advantages of dependency injection.</p>
<ul>
<li>Your code is modular.</li>
<li>Classes are not having any strong reference to another class.</li>
<li>You are able to test your code independently.</li>
</ul>
<p>The container which supports this dependency injection concept is called the I<strong>OC (Inversion of control) Container</strong>. Spring uses the concept of IOC and dependency injection to locate and inject services for you. Spring allows you to write your classes without having any dependency code .</p>
<p>There are three different ways dependencies can be injected.</p>
<ul>
<li>Constructor Injection (CI) - Dependencies (say , other class references) can be injected as a parameter to the constructor of a class. Hence no hard code object creation of the Dependent class is needed.</li>
<li>Setter Injection (SI) - Inject the dependency as a setter method of the class</li>
<li>Interface Injection (II) &#8211; interface injection, in which the exported module provides an interface that its users must implement in order to get the dependencies at runtime.</li>
</ul>
<p>
A design based on independent classes / components increases the re-usability and possibility to test the software. For example if a class A expects a Dao (Data Access object) for receiving the data from a database you can easily create another test object which mocks the database connection and inject this object into A to test A without having an actual database connection.<br />
</P></p>
<p>Have look at the Bean dependency in detail <a href="http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-properties-detailed" target="_blank">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%2Fdependency-injection-concept%2F&amp;linkname=Dependency%20Injection%20Concept"><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/dependency-injection-concept/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
