VietTuts

Tự Học Lập Trình Online

  • Home
  • Java
  • Servlet
  • JSP
  • Struts2
  • Hibernate
  • Spring
  • MyBatis
  • Java WS
  • C
  • C++
  • C#
  • Python
  • PHP
  • Excel
  • VBA
  • Web
    • JavaScript
    • JQUERY
    • JSON
    • AJAX
    • CSS
    • HTML
    • HTML5
    • Node.js
    • Angular 7
  • SQL
    • MySQL
    • SQL Server
  • Misc
    • Eclipse
    • Phần mềm tiện ích
    • Cấu trúc DL&GT
    • Selenium Test

Spring Tuts

Spring là gì? Kiến trúc Spring Spring - Thiết lập môi trường Spring HelloWorld Example Dependency Injection trong Spring IoC Containers trong Spring Định nghĩa Bean trong Spring Phạm vi của Bean trong Spring Vòng đời của Bean trong Spring Spring - Kế thừ Bean Spring - Inner Bean Spring - Injecting Collection Spring - Beans Auto-Wiring Annotation Based Configuration Spring - Java Based Configuration Spring - Event Handling in Spring Spring - Custom Events in Spring Spring - AOP with Spring Framework Spring - JDBC Framework Spring - Transaction Management Spring - Web MVC Framework Spring - Logging with Log4J

Spring Tool

Cài đặt Spring Tool Suite (STS) trong Eclipse Tạo Spring project bằng Spring Tool Suite trong Eclipse Tạo Spring project (annotation) bằng Spring Tool Suite (STS)

Spring 4 Example

Ví dụ login trong Spring 4 Web MVC – Hibernate 4 XML Mapping Ví dụ login trong Spring 4 Web MVC – Hibernate 4 Annotation
1 / 3
❮ ❯

Injecting Collection trong Spring


Previous
Next

Như bạn đã thấy cách cấu hình kiểu dữ liệu nguyên thủy bằng cách sử dụng thuộc tính value và tham chiếu đối tượng bằng cách sử dụng thuộc tính ref của thẻ <property> trong file cấu hình Bean.

Spring cung cấp 4 loại phần tử để cấu hình các đối tượng Collection:

No. Phần tử & Mô tả
1

<list>

Phần tử này giúp tiêm một danh sách các giá trị cho đối tượng List, cho phép trùng lặp.

2

<set>

Phần tử này giúp tiêm một danh sách các giá trị cho đối tượng Set, KHÔNG cho phép trùng lặp.

3

<map>

Phần tử này giúp tiêm một tập hợp các cặp tên-giá trị trong đó tên và giá trị có thể thuộc bất kỳ kiểu dữ liệu nào.

4

<props>

một tập hợp các cặp tên-giá trị trong đó tên và giá trị đều là String

Cũng giống như các đối tượng khác trong Spring, bạn có thể truyền giá trị cho đối tượng Collection bằng 2 cách:

  • Sử dụng thuộc tính value, truyền giá trị trực tiếp cho đối tượng Collection.
  • Sử dụng thuộc tính ref, tham chiếu tới một bean khác.

Nội dung chính

  • Ví dụ Injecting Collection trong Spring
  • Injecting Bean tham chiếu
  • Injecting giá trị rỗng và giá trị null
  • Download Project

Ví dụ Injecting Collection trong Spring

Tạo một Java Maven project trong Eclipse.

Cấu trúc project:

Injecting Collection trong Spring

Sau đó update file pom.xml để tải thư viện Spring như sau:

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>vn.viettuts</groupId>
  <artifactId>SpringExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringExample</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.6.RELEASE</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
  </dependencies>
</project>

Đây là nội dung của file JavaCollection.java

package vn.viettuts.example;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class JavaCollection {
    private List addressList;
    private Set addressSet;
    private Map addressMap;
    Properties addressProp;

    public void setAddressList(List addressList) {
        this.addressList = addressList;
    }
    public List getAddressList() {
        System.out.println("List Elements :" + addressList);
        return addressList;
    }
    public void setAddressSet(Set addressSet) {
        this.addressSet = addressSet;
    }
    public Set getAddressSet() {
        System.out.println("Set Elements :" + addressSet);
        return addressSet;
    }
    public void setAddressMap(Map addressMap) {
        this.addressMap = addressMap;
    }
    public Map getAddressMap() {
        System.out.println("Map Elements :" + addressMap);
        return addressMap;
    }
    public void setAddressProp(Properties addressProp) {
        this.addressProp = addressProp;
    }
    public Properties getAddressProp() {
        System.out.println("Property Elements :" + addressProp);
        return addressProp;
    }
}

Đây là nội dung của file MainApp.java

package vn.viettuts.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello world!
 *
 */
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "Beans.xml");
        JavaCollection jc = (JavaCollection) context.getBean("javaCollection");
        jc.getAddressList();
        jc.getAddressSet();
        jc.getAddressMap();
        jc.getAddressProp();
    }
}

Sau đây là tệp cấu hình Beans.xml có cấu hình cho tất cả các đối tượng Collection:

<?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-3.0.xsd">
 
  <!-- Definition for javaCollection -->
   <bean id = "javaCollection" class = "vn.viettuts.example.JavaCollection">
      
      <!-- list các giá trị này được gán cho addressList -->
      <property name = "addressList">
         <list>
            <value>Ha Noi</value>
            <value>Vinh Phuc</value>
            <value>Bac Ninh</value>
         </list>
      </property>

      <!-- list các giá trị này được gán cho addressSet -->
      <property name = "addressSet">
         <set>
            <value>Ha Noi</value>
            <value>Vinh Phuc</value>
            <value>Bac Ninh</value>
         </set>
      </property>

      <!-- list các giá trị này được gán cho addressMap -->
      <property name = "addressMap">
         <map>
            <entry key = "1" value = "Ha Noi"/>
            <entry key = "2" value = "Vinh Phuc"/>
            <entry key = "3" value = "Bac Ninh"/>
         </map>
      </property>
      
      <!-- list các giá trị này được gán cho addressProp -->
      <property name = "addressProp">
         <props>
            <prop key = "one">Ha Noi</prop>
            <prop key = "one">Ha Noi</prop>
            <prop key = "two">Vinh Phuc</prop>
            <prop key = "three">Bac Ninh</prop>
         </props>
      </property>
   </bean>
</beans>

Injecting Bean tham chiếu

Định nghĩa Bean sau đây sẽ giúp bạn hiểu cách chèn các bean tham chiếu như một phần tử của đối tượng Collection. Thậm chí bạn có thể kết hợp tất cả tham chiếu và giá trị với nhau.

?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-3.0.xsd">

   <bean id = "..." class = "...">

      <!-- Truyền tham chiếu bean cho java.util.List -->
      <property name = "addressList">
         <list>
            <ref bean = "address1"/>
            <ref bean = "address2"/>
            <value>Pakistan</value>
         </list>
      </property>
      
      <!-- Truyền tham chiếu bean cho java.util.Set -->
      <property name = "addressSet">
         <set>
            <ref bean = "address1"/>
            <ref bean = "address2"/>
            <value>Pakistan</value>
         </set>
      </property>
      
      <!-- Truyền tham chiếu bean cho java.util.Map -->
      <property name = "addressMap">
         <map>
            <entry key = "one" value = "INDIA"/>
            <entry key = "two" value-ref = "address1"/>
            <entry key = "three" value-ref = "address2"/>
         </map>
      </property>
   </bean>
</beans>

Kết quả:

List Elements :[Ha Noi, Vinh Phuc, Bac Ninh]
Set Elements :[Ha Noi, Vinh Phuc, Bac Ninh]
Map Elements :{1=Ha Noi, 2=Vinh Phuc, 3=Bac Ninh}
Property Elements :{two=Vinh Phuc, one=Ha Noi, three=Bac Ninh}

Injecting giá trị rỗng và giá trị null

Nếu bạn cần truyền một chuỗi rỗng dưới dạng một giá trị, thì bạn có thể truyền nó như sau:

<bean id = "..." class = "exampleBean">
   <property name = "email" value = ""/>
</bean>

Ví dụ trước tương đương với mã Java: exampleBean.setEmail("")

Nếu bạn cần truyền một giá trị NULL, thì bạn có thể truyền nó như sau:

<bean id = "..." class = "exampleBean">
   <property name = "email"><null/></property>
</bean>

Ví dụ trước tương đương với mã Java: exampleBean.setEmail(null)


Download Project

Download Now!

Previous
Next

Recent Updates

SpringLayout trong Java SwingMyBatis Example - MyBatis + SpringSpring là gì?Cài đặt Spring Tool Suite (STS) trong EclipseDependency Injection trong SpringĐịnh nghĩa Bean trong SpringInjecting Collection trong SpringInner Bean trong SpringIoC Container trong SpringKế thừa Bean trong SpringKiến trúc SpringPhạm vi của Bean trong SpringSắp Tết 2026 Rồi! - Còn bao nhiêu ngày nữa là đến tết 2026?

VietTuts on facebook

Học Lập Trình Online Miễn Phí - VietTuts.Vn
Danh Sách Bài Học

Học Java | Hibernate | Spring
Học Excel | Excel VBA
Học Servlet | JSP | Struts2
Học C | C++ | C#
Học Python
Học SQL

Bài Tập Có Lời Giải

Bài tập Java
Bài tập C
Bài tập C++
Bài tập C#
Bài tập Python
Ví dụ Excel VBA

Câu Hỏi Phỏng Vấn

201 câu hỏi phỏng vấn java
25 câu hỏi phỏng vấn servlet
75 câu hỏi phỏng vấn jsp
52 câu hỏi phỏng vấn Hibernate
70 câu hỏi phỏng vấn Spring
57 câu hỏi phỏng vấn SQL

Scroll back to top

Copyright © 2016 VietTuts.Vn all rights reserved. | Liên hệ | Chính sách - riêng tư | sitemap.html | sitemap_index.xml