Showing posts with label download-source-code. Show all posts
Showing posts with label download-source-code. Show all posts

Thursday, 17 March 2011

Spring Constructor Dependency Injection tutorial (Xml approach)

In this example you will learn how to set a bean property via constructor injection. Here we use User:

class User{
private String name;
private int age;
private String country;
public User( String name, int age) {
this.name=name;
this.age=age;
}
public String toString() {
return name+" "+age;
}

}


The User bean class has two attributes viz. name and age. All the attributes are set through constructor injection. The toString() method of the User bean class is overridden to display the user object, in the main method.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.vaani.bean.User" >
<constructor-arg value="Kinshuk" />
<constructor-arg value="24"/>
</bean>
</beans>
Here the beans.xml file is used to do spring bean configuration. The following code shows how to set a property value thru constructor injection. We use <constructor-arg> to set the values.
Note – We have initialized the properties in the User bean in the order in which they occur in the constructor, i.e. first Name comes and then Age. But this is not it. We have many cases, which we have to deal. Lets deal with them one by one.

Case when Number of arguments in the constructor are equal and of the primary type

The constructor-arg element within the bean element is used to set the property value thru constructor injection. Since there is only one constructor in the User bean class, this code will work fine. When there is more than one constructor with the same number of arguments, then the following ambiguities will occur. Consider the following code:
class User{
private String name;
private int age;
private String country;
public User( int age, String country) {
this.age=age;
this.country=country;
}
public User(String name, String country) {
this.name=name;
this.country=country;
}
}

Now in bean descriptor file :

<bean id="user" class="com.vaani.bean.User" >
<constructor-arg value="24"/>
<constructor-arg value="India"/>
</bean>

Now which constructor do you think will be invoked? The first one with the int and the String argument, right? But for your surprise it will call the second constructor with both String arguments. Though we know the first argument is of type int and the second argument is of type String, spring interprets both as String arguments. To avoid this confusion you need to specify the type attribute of the constructor-arg element. Now with the following bean configuration, the first constructor will be invoked.

<bean id="user" class="com.vaani.bean.User" >
<constructor-arg type="int" value="24"/>
<constructor-arg type="java.lang.String" value="India"/>
</bean>


Case when constructor has same argument types , but in different order

Now consider this case. We have the following constructors in the User bean class.
public User(String name, int age)
{
this.name=name;
this.age=age;
}
public User( int age, String country)
{
this.age=age;
this.country=country;
}
The bean configuration file :
<bean id="user" class="com.vaani.bean.User" >
<constructor-arg type="int" value="24"/>
<constructor-arg type="java.lang.String" value="India"/>
</bean>

Now which constructor do you think will be called? The second constructor, right? But again for your surprise the first constructor will be called, this is because the order in which the arguments appear in the bean configuration file will not be considered while invoking the constructor. To solve this problem you can use the index attribute to specify the constructor argument index.

Here is the bean configuration file after adding the index attribute:

<bean id="user" class="com.vaani.bean.User" >
<constructor-arg index="0" type="int" value="24"/>
<constructor-arg index="1" type="java.lang.String" value="India"/>
</bean>
Now as expected, the second constructor will be invoked.

Summary


Constructor injection can be done through <constructor-arg>.Also, we came to now about attributes of <constructor-arg> – type and index.


Download the Source


Source can be downloaded from here.

Spring : Setter Dependency Injection(Xml approach)

In this example you will learn how to set a bean property via setter injection. Consider the bean here :

package com.vaani.spring.beans;
public class ExampleBean
{
private String s;
private int i;

public void setStringProperty(String s) { this.s = s; }
public void setIntegerProperty(int i) { this.i = i; }
}
Now the above bean has 2 attributes – String s and int i. Now the bean has corresponding setters in it.

Bean Configuration file – Using property and value tags
Here the beans.xml file is used to do spring bean configuration. The following code shows how to set a property value through setter injection.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
>
<!--inject the ExampleBean -->
<!-- -->
<bean id="exampleBean" class="com.vaani.spring.ExampleBean">
<property name="stringProperty">
<value>Hi!</value>
</property>
<property name="integerProperty">
<value>1</value>
</property>
</bean>
</beans>

The id attribute of the bean element is used to specify the bean name and the class attribute is used to specify the fully qualified class name of the bean. The property element with in the bean element is used to inject property value via setter injection. The name attribute of the property element represents the bean attribute and the value attribute specifies the corresponding property value.
Note – To do setter injection we need to have a setter in the class, such that its name is derived as setAbc, than in spring you should name property as abc.
Here we set "Hi!" and "1" for the example bean. properties – s and i respectively.

Download the source

The Example can be downloaded from here.


DI when properties are not simple types


So here ref comes into picture. Example for passing property value as an another bean

package com.vaani.spring;
public class ExampleBean
{
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
public void setBeanOne(AnotherBean b) {
beanOne = b;
}
public void setBeanTwo(YetAnotherBean b) {
beanTwo = b;
}
}
In the XML bean descriptor file:

<bean id="exampleBean" class="com.vaani.spring.ExampleBean">
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
</bean>
We can refer these beans by using getBeans method , like we did it here.
Note that we are doing ref bean= and then referring to bean.

Download the source


You can download the source code from here.

Spring IOC or DI - Reducing coupling

In Spring, the Inversion of Control (IoC) principle is implemented using the Dependency Injection (DI) design pattern. But note that In spring framework both terms are used interchangeably. Let's understand dependency injection with the help of an example.

Example of Tight Coupling

The QuizMater interface exposes the popQuestion() method. To keep things simple, our QuizMaster will generate only one question.

Getting the interface ready
QuizMaster.java
package com.vaani.bean.quizmaster;

public interface QuizMaster {

public String popQuestion();
}

Getting the implementations ready
The StrutsQuizMaster and the SpringQuizMaster class implements QuizMaster interface and they generate questions related to struts and spring respectively.
StrutsQuizMaster.java 
public class StrutsQuizMaster implements QuizMaster {

@Override
public String popQuestion() {

return "Are you new to Struts?";

}

}
SpringQuizMaster.java
public class SpringQuizMaster implements QuizMaster {

@Override
public String popQuestion() {
return "Are you new to Spring?";
}
}
We have a QuizMasterService class that displays the question to the user. The QuizMasterService class holds reference to the QuizMaster.
public class QuizMasterService {

private QuizMaster quizMaster = new SpringQuizMaster();

public void askQuestion()
{
System.out.println(quizMaster.popQuestion());
}
}
Finally we create the QuizProgram class to conduct quiz.
public class QuizProgram {

public static void main(String[] args) {
QuizMasterService quizMasterService = new QuizMasterService();
quizMasterService.askQuestion();
}

}
As you can see it is pretty simple, here we create an instance of the QuizMasterService class and call the askQuestion() method. When you run the program as expected "Are you new to Spring?" gets printed in the console.
Let's have a look at the class diagram of this example. The green arrows indicate generalization and the blue arrows indicates association.


spring dependency injection1

As you can see this architecture is tightly coupled. We create an instance of the QuizMaster in the QuizMasterService class in the following way.
private QuizMaster quizMaster = new SpringQuizMaster();
To make our quiz master Struts genius we need to make modifications to the QuizMasterService class like this.
private QuizMaster quizMaster = new StrutsQuizMaster();

So it is tightly coupled. Also we have to hard-code the stuff here. This is not good for development environments, because we have again and again change code for some simple stuff. Now lets see how we can avoid this by using the Dependency Injection design pattern.


How to reduce tight coupling here?
So the solution we can think of is either use factory pattern. But still we will see another method called DI or dependency injection is far better than factory pattern.


Reducing coupling via Factory Pattern


Now one solution to this is factory pattern.We can make a factory class, which produces all beans for us.
Beans in the example there were SpringQuizMaster and StrutsQuizMaster.
First of all we can create the factory:

public class QuizMasterFactory {
public static QuizMaster getQuizMaster(String subject)
{
if("Spring".equals(subject))
return new SpringQuizMaster();
else if("Struts".equals(subject))
return new StrutsQuizMaster();
else
throw new IllegalArgumentException("No subject exists with name "+subject);
}
}

Now you should get your service ready.And in service we can simply do this:
public class QuizMasterServiceFromFactory {

QuizMaster quizMaster;

public void setQuizMaster(QuizMaster quizMaster) {
this.quizMaster = quizMaster;
}

public void askQuestion()
{
System.out.println(quizMaster.popQuestion());
}
}
Now in main method we can do:

public static void main(String[] args) {
QuizMaster quizMaster = QuizMasterFactory.getQuizMaster("Spring");
QuizMasterServiceFromFactory quizMasterService = new QuizMasterServiceFromFactory();
quizMasterService.setQuizMaster(quizMaster);

quizMasterService.askQuestion();
}

But still if there is still new requirement, to add other beans like HibernateQuizMaster...we have to edit  this factory class as well, so still have to build and all that stuff. So here comes spring in picture.
The Spring framework provides prowerful container to manage the components. The container is based on the Inversion of Control (IoC) principle and can be implemented by using the Dependency Injection (DI) design pattern. Here the component only needs to choose a way to accept the resources and the container will deliver the resource to the components.
So now we do this by spring to reduce coupling.


Spring Method or reducing coupling via DI or IOC


The value for the QuizMaster will be set using the setQuizMaster() method. The QuizMaster object is never instantiated in the QuizMasterService class, but still we access it. Usually this will throw a NullPointerException, but here the container will instantiate the object for us, so it works fine.
Now consider this service, which refer these beans, but have now nothing to worry about how to create beans :


public class QuizMasterServiceSpring {

QuizMaster quizMaster;

public void setQuizMaster(QuizMaster quizMaster) {
this.quizMaster = quizMaster;
}

public void askQuestion()
{
System.out.println(quizMaster.popQuestion());
}
}

 


After making all the changes, the class diagram of the example look like this.

dependency injection reduction spring


The container comes into picture and it helps in injecting the dependancies.
The bean configuration is done in the beans.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="springQuizMaster" class="com.vaani.spring.quizmaster.SpringQuizMaster"></bean>
<bean id="strutsQuizMaster" class="com.vaani.spring.quizmaster.StrutsQuizMaster"></bean>
<bean id="quizMasterService" class="com.vaani.spring.quizmaster.QuizMasterService">
<property name="quizMaster">
<ref local="springQuizMaster"/>
</property>
</bean>

</beans>

We define each bean using the bean tag. The id attribute of the bean tag gives a logical name to the bean and the class attribute represents the actual bean class. The property tag is used to refer the property of the bean. To inject a bean using the setter injection you need to use the ref tag.
Here a reference of SpringQuizMaster is injected to the QuizMaster bean. When we execute this example, "Are you new to Spring?" gets printed in the console.
To make our QuizMaster ask questions related to Struts, the only change we need to do is, to change the bean reference in the ref tag.

<bean id="quizMasterService" class="com.vaani.spring.quizmaster.QuizMasterService">
<property name="quizMaster">
<ref local="strutsQuizMaster"/>
</property>
</bean>


In this way the Dependency Injection helps in reducing the coupling between the components.
To execute this example add the following jar files to the classpath.


  • antlr-runtime-3.0
  • commons-logging-1.0.4
  • org.springframework.asm-3.0.0.M3
  • org.springframework.beans-3.0.0.M3
  • org.springframework.context-3.0.0.M3
  • org.springframework.context.support-3.0.0.M3
  • org.springframework.core-3.0.0.M3
  • org.springframework.expression-3.0.0.M3

So instead of changing code in java, we have to change the xml only, whenever the need be. Also from the spring example, it was clear why we call it inversion of control. Because we needed beans in the service, we have to first define and initiate these beans, and then give it to service class. But beauty of spring is that we don't have to worry about how spring will initialize these beans. We can provide beans in any order and spring will determine how to initialize those. See other dependency injection frameworks.

Download the Source


You can download the source code with "Tight coupled" Quizmaster here.

You can download the source code of Factory method pattern solving coupling problem here.

Also you can finally download the whole example with spring from here.