Spring Core – Phần 4: Spring Dependency Injection với Object, Collections, Map

Spring Core – Phần 4: Spring Dependency Injection với Object, Collections, Map

1. Spring DI với Object (Dependent Object)

Trường hợp mối quan hệ giữa các class là has-a (1 đối tượng chứa 1 đối tượng khác) chúng ta sẽ tạo bean cho đối tượng bên trong và truyền nó vào hàm khởi tạo hoặc setter.

Spring Core – Phần 4: Spring Dependency Injection với Object, Collections, Map

Ví dụ dưới đây là trường hợp Person has-a Address (một person có một address bên trong):

public class Address {
  private String country;
  private String province;
  private String district;

  public Address() {
  }

  public Address(String country, String province, String district) {
    this.country = country;
    this.province = province;
    this.district = district;
  }

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  public String getProvince() {
    return province;
  }

  public void setProvince(String province) {
    this.province = province;
  }

  public String getDistrict() {
    return district;
  }

  public void setDistrict(String district) {
    this.district = district;
  }

  @Override
  public String toString() {
    return "Address [country=" + country + ", province=" + province + ", district=" + district + "]";
  }

}
public class Person {
  private String name;
  private int age;
  private Address address;

  public Person() {
  }

  public Person(String name, int age, Address address) {
    this.name = name;
    this.age = age;
    this.address = address;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Address getAddress() {
    return address;
  }

  public void setAddress(Address address) {
    this.address = address;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public void print() {
    System.out.println("Person: " + this.name + " Age: " + this.age + " Address: " + this.address.toString());
  }

}

Trong file cấu hình ta sẽ tạo bean cho đối tượng Address và truyền nó vào bean của đối tượng Person:

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">

  <!-- Inject by setter -->
  <bean id="person" class="stackjava.com.springdiobject.demo.Person">
    <property name="name" value="stackjava.com"></property>
    <property name="age" value="25"></property>
    <property name="address" ref="address"></property>
  </bean>

  <!-- Inject by constructor -->
  <bean id="person2" class="stackjava.com.springdiobject.demo.Person">
    <constructor-arg name="name" type="String" value="spring"></constructor-arg>
    <constructor-arg name="age" type="int" value="30"></constructor-arg>
    <constructor-arg name="address" ref="address"></constructor-arg>
  </bean>

  <bean id="address" class="stackjava.com.springdiobject.demo.Address">
    <property name="country" value="Viet Nam"></property>
    <property name="province" value="Ha Noi"></property>
    <property name="district" value="Thanh Xuan"></property>
  </bean>

</beans>

Demo:

public class MainApp {
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Person person= (Person) context.getBean("person");
    person.print();

    Person person1 = (Person) context.getBean("person2");
    person1.print();

  }
}

Kết quả:

Person: stackjava.com Age: 25 Address: Address [country=Viet Nam, province=Ha Noi, district=Thanh Xuan]
Person: spring Age: 30 Address: Address [country=Viet Nam, province=Ha Noi, district=Thanh Xuan]

Download code ví dụ trên tại đây

2. Spring DI với Collections (Dependent Collections)

Tương tự ví dụ trên nhưng đối tượng Person có nhiều Address, nhiều email:

public class Person {
  private String name;
  private int age;
  private List<Address> addresses;
  private List<String> emails;

  public Person() {
  }

  public Person(String name, int age, List<Address> addresses, List<String> emails) {
    this.name = name;
    this.age = age;
    this.addresses = addresses;
    this.emails = emails;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public List<Address> getAddresses() {
    return addresses;
  }

  public void setAddresses(List<Address> addresses) {
    this.addresses = addresses;
  }

  public List<String> getEmails() {
    return emails;
  }

  public void setEmails(List<String> emails) {
    this.emails = emails;
  }

  public void print() {
    System.out.println("Person: " + this.name + " Age: " + this.age);
    System.out.println("Address: ");
    for (Address address : addresses) {
      System.out.println(address);
    }
    System.out.println("Email:");
    for (String email : emails) {
      System.out.println(email);
    }
    System.out.println("++++++++++++++++++++++++++++++++++");
  }

}

File cấu hình 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">


  <!-- Inject by constructor -->
  <bean id="person2" class="stackjava.com.springdicollections.demo.Person">
    <constructor-arg name="name" type="String" value="spring"></constructor-arg>
    <constructor-arg name="age" type="int" value="30"></constructor-arg>
    <constructor-arg name="addresses">
      <list>
        <ref bean="address1" />
        <ref bean="address2" />
      </list>
    </constructor-arg>
    <constructor-arg name="emails">
      <list>
        <value>abc@gmail.com</value>
        <value>def@yahoo.com</value>
      </list>
    </constructor-arg>
  </bean>

  <!-- Inject by setter -->
  <bean id="person" class="stackjava.com.springdicollections.demo.Person">
    <property name="name" value="stackjava.com"></property>
    <property name="age" value="25"></property>
    <property name="addresses">
      <list>
        <ref bean="address2" />
      </list>
    </property>
    <property name="emails">
      <list>
        <value>ghi@hotmail.com</value>
        <value>klm@zzz.com</value>
      </list>
    </property>

  </bean>

  <bean id="address1" class="stackjava.com.springdicollections.demo.Address">
    <property name="country" value="Viet Nam"></property>
    <property name="province" value="Ha Noi"></property>
    <property name="district" value="Thanh Xuan"></property>
  </bean>
  <bean id="address2" class="stackjava.com.springdicollections.demo.Address">
    <property name="country" value="Viet Nam"></property>
    <property name="province" value="Ha Noi"></property>
    <property name="district" value="Ha Dong"></property>
  </bean>

</beans>

Demo:

public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  Person person = (Person) context.getBean("person");
  person.print();

  Person person1 = (Person) context.getBean("person2");
  person1.print();

}

Kết quả:

Person: stackjava.com Age: 25
Address: 
Address [country=Viet Nam, province=Ha Noi, district=Ha Dong]
Email:
ghi@hotmail.com
klm@zzz.com
++++++++++++++++++++++++++++++++++
Person: spring Age: 30
Address: 
Address [country=Viet Nam, province=Ha Noi, district=Thanh Xuan]
Address [country=Viet Nam, province=Ha Noi, district=Ha Dong]
Email:
abc@gmail.com
def@yahoo.com
++++++++++++++++++++++++++++++++++

 

Okay Done!

Các trường hợp dùng với Set, Map tương tự như List.

Download code ví dụ trên tại đây

Bài tiếp theo chúng ta sẽ tìm hiểu về Spring AOP.

Thanks các bạn đã theo dõi!

 

References: https://www.javatpoint.com/spring-tutorial

stackjava.com