English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

l'héritage de bean Spring

en utilisant bean de parent Les attributs, nous pouvons spécifier les relations d'héritage entre les beans. Dans ce cas, la valeur du bean parent sera héritée par le bean courant.

Laissez-nous voir un exemple simple d'héritage de bean.

Employee.java

Cette classe contient trois attributs, trois constructeurs et la méthode show() pour afficher les valeurs.

package com.w3codebox;
public class Employee {
private int id;
private String name;
private Address address;
public Employee() {}
public Employee(int id, String name) {
    super();
    this.id = id;
    this.name = name;
}
public Employee(int id, String name, Address address) {
    super();
    this.id = id;
    this.name = name;
    this.address = address;
}
void show(){
    System.out.println(id+" ""+nom);
    System.out.println(address);
}
}

Address.java

package com.w3codebox;
public class Address {
private String addressLine1, ville, state, country;
public Address(String addressLine1, String ville, String state, String country) {
    super();
    this.addressLine1 = addressLine1;
    this.city = ville;
    this.state = state;
    this.country = country;
}
public String toString(){
    return addressLine1+" ""+ville+" ""+state+" ""+country;
}
}

applicationContext.xml

<?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:p="http://www.springframework.org/schema/p
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e1" class="com.w3codebox.Employee">
<constructeur-arg value="101"><//constructeur-arg>
<constructeur-arg value="Sachin"></constructeur-arg>
</bean>
<bean id="adresse1" class="com.w3codebox.Address">
<constructeur-arg value="21,Lohianagar"></constructeur-arg>
<constructeur-arg value="Ghaziabad"></constructeur-arg>
<constructeur-arg value="UP"></constructeur-arg>
<constructeur-arg value="USA"></constructeur-arg>
</bean>
<bean id="e2" class="com.w3codebox.Employee" parent="e1">
<constructeur-arg ref="adresse1"><//constructeur-arg>
</bean>
</beans>

Test.java

Cette classe récupère le Bean à partir du fichier applicationContext.xml et appelle la méthode show.

package com.w3codebox;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
    Resource r=new ClassPathResource("applicationContext.xml");
    BeanFactory factory=new XmlBeanFactory(r);
    
    Employee e1=(Employee)factory.getBean("e2");
    e1.show();
    
}
}