WELCOME Abdennour : Software engineer

Dec 10, 2011

Tuto HelloWorld :Dependency Injection With Spring

Introduction:
Spring is the most popular application development framework for enterprise Java™.

Dependency injection (DI) is a design pattern in object-oriented computer programming whose purpose is to improve testability of, and simplify deployment of components in large software systems.
1. With One Class:

In this example you will learn how to set a bean property via setter injection. Consider the following Client bean class.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package org.toumi.domain;
public class Client {
private String nom;
private int age;
private ICommande commande;
public Client(){}
public Client(String nom, int age) {
super();
this.nom = nom;
this.age = age;
}
public ICommande getCommande() {
return commande;
}
public void setCommande(ICommande commande) {
this.commande = commande;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Client [nom=" + nom + ", age=" + age + "]";
}
}

The Cleint bean class has two attributes viz.nom and age. All the two attributes are set using the setter injection. The toString() method of the Client bean class is overridden to display the user object.

Here the applicationcontext.xml file is used to do spring bean configuration. The following code shows how to set a property value thru 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"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

<bean id="client" class="org.toumi.domain.Client" >
      <property name="nom" value="Abdesslem"></property>
       <property name="age" value="16"></property>
</bean>
</beans>

Or we can use alias p(property)

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


      <bean id="client" class="org.toumi.domain.Client" p:nom="Abdesslem" p:age="16" >


         </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.

 Here we set "Abdesslem" and "16"  for the Client bean properties nom and age respectively. The following Main class is used to get the Client bean from the Spring IoC container and dispaly its value it to the client.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package org.toumi.client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.toumi.domain.Client;
public class UtilisationClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
         //Sans Service Spring
/*Client client=new Client();
client.setNom("Abdesslem");
client.setAge(16);
System.out.println(client.toString());*/
//Avec Spring
ApplicationContext contexte = new ClassPathXmlApplicationContext("applicationcontext.xml");
Client client= (Client)contexte.getBean("client");
System.out.println(client);
}
}

On executing the Main class the following message gets displayed on the console.
Client [nom=Abdesslem, age=16]


  2. Used an other Class Command Which is in association with Client:
       a-Without reliable coupling:(without interface for Commande)
In this example you will learn how to refer a bean to an other bean via setter injection. Consider the following Commande bean class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package org.toumi.domain;
public class Commande {
private float montant;
/* (non-Javadoc)
* @see org.toumi.domain.ICommande#getMontant()
*/
@Override
public float getMontant() {
return montant;
}
/* (non-Javadoc)
* @see org.toumi.domain.ICommande#setMontant(float)
*/
@Override
public void setMontant(float montant) {
this.montant = montant;
}
/* (non-Javadoc)
* @see org.toumi.domain.ICommande#lancerCommande()
*/
@Override
public void lancerCommande(){
System.out.println("C'est fait, La commande est lancée, votre mantant est "
+montant);
}
}
 
           Here the applicationcontext.xml file is used to do spring bean configuration. The following code shows how to refer a bean  to an other.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="client" class="org.toumi.domain.Client" p:nom="Abdesslem" p:age="16" p:commande-ref="commande" />
  
<bean id="commande" class="org.toumi.domain.Commande" p:montant="100.5" />
</beans>



Run the following code 



public static void main(String[] args) {
ApplicationContext contexte = new ClassPathXmlApplicationContext("applicationcontext.xml");
Client client= (Client)contexte.getBean("client");
//System.out.println(client);
client.getCommande().lancerCommande();
}

the following message gets displayed on the console.

C'est fait, La commande est lancée, votre mantant est 100.5


b-With reliable coupling(With Interface & implementations)
-you will extract intrface ICommande from Commande Class.
-Rename the Class Commande to CommandeLache
-And Copy/Paste this Class and Rename to CommandeFermee
-We have now an Interface with two implementation(CommandeFerme,CommandeLache).
-To differentiate between the two classes, will modify the function lancerCommande
In CommandeFerme,you will update :



public void lancerCommande(){
System.out.println("C'est fait, La commande fermée est lancée, votre mantant est "+montant);
}


For CommandeLache,you will update


public void lancerCommande(){
System.out.println("C'est fait, La commande Lache est lancée, votre mantant est "+montant);
}



REMARQUE(IMPORTANT)

A la fin de la construction des singletons(beans) par Spring, on a un objet de type [Client] qui a son champ [Commande] initialisé sans qu'il sache comment. On dit qu'on a injecté de la dépendance dans l'objet [Client]. On dit également qu'on a inversé le contrôle : ce n'est plus l'objet [Client]
qui prend l'initiative de créer lui-même l'objet implémentant l'interface [ICommande] dont il a besoin, c'est l'application au plus
haut niveau (lorsqu'elle s'initialise) qui prend soin de créer tous les objets dont elle a besoin en gérant les dépendances de ceux-ci
entre-eux.




Clutch Metaphor(fr:métaphore d'embrayage)

Embrayage @Abdennour Toumi Génie logiciel

:

Here the applicationcontext.xml file is used to do spring bean configuration. The following code shows how to refer a bean  to an other.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean id="client" class="org.toumi.domain.Client" p:nom="Abdesslem" p:age="16" p:commande-ref="commande2" >
  
</bean>
<bean id="commande1" class="org.toumi.domain.CommandeFerme" p:montant="100.5" />
<bean id="commande2" class="org.toumi.domain.CommandeLache" p:montant="122.5" />
</beans>
==>to engage the clutch, I change the value of p:commande-ref by commande1 or commande2


Remarque:L'intérêt principal de la configuration du singleton [Client] par un fichier Spring, est que maintenant on
peut changer la classe d'implémentation correspondant au champ [commande] de la classe [Commande] sans
que le code de celle-ci soit modifié. Il suffit de changer le nom de la classe dans la définition au bean [commande] dans le fichier
Spring (CommandeLache,CommandeFerme)


3. Video Tutorial:

Part1 : 



Part2:







  4. Source Code (with Library Spring):






http://www.mediafire.com/?u94rx0sdio8jmaf

1 comment: