Java如何使用Spring EL访问集合成员?

在本文中,您将看到Spring EL的另一个强大示例。我们将演示如何使用Spring EL访问集合成员。

通过使用Spring EL,您可以选择集合中的单个引用成员。您还可以根据属性的值选择集合的成员。您可以做的另一件事是从集合成员中提取属性以创建另一个集合对象。

为了说明这一点,我们将创建一个简单的bean / pojo作为我们的集合对象。我们将创建一个Book类的一些属性(id,title,author)。

package org.nhooo.example.spring.el;

public class Book {
    private Long id;
    private String title;
    private String author;
    private String type;

    // Getters & Setters
}

接下来,我们需要创建spring配置文件。在此配置中,我们将使用<util:list>元素创建书籍的集合。并且我们还创建了一个其属性是从集合对象之一获得的bean。

<?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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <util:list id="books">
        <bean
                p:title="Essential C# 4.0" p:author="Michaelis"/>
        <bean
              p:title="User Stories Applied" p:author="Mike Cohen"/>
        <bean
              p:title="Learning Android" p:author="Marco Gargenta"/>
        <bean
              p:title="The Ruby Programming Language"
              p:author="David Flanagan & Yukihiro Matsumoto"/>
        <bean
              p:title="Einstein" p:author="Walter Isaacson"/>
    </util:list>

    <bean id="book">
        <property name="title" value="#{books[3].title}"/>
        <property name="author" value="#{books[3].author}"/>
    </bean>

</beans>

在配置上面你已经看到了我们是如何设置title和author对的book豆。我们使用方括号运算符([])通过其索引访问集合的成员。看起来像这样:

<property name="title" value="#{books[3].title}"/>
<property name="author" value="#{books[3].author}"/>

可以理解为:请给我收集对象的索引号,3并取其值title并将author其分配给bookbean。您可能已经知道Java中的集合对象始终是从零开始的索引。因此,这将给我们提供标题为“ The Ruby Programming Language”的书

最后,让我们创建一个示例类,以运行上面的spring配置。只需加载spell-collection.xml我们在上面创建的配置。从已加载的bean中获取一个bean,ApplicationContext并打印出其属性title和author属性。

package org.nhooo.example.spring.el;

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

public class SpELCollectionExample {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-collection.xml");

        Book book = (Book) context.getBean("book");
        System.out.println("book.getTitle() = " + book.getTitle());
        System.out.println("book.getAuthor() = " + book.getAuthor());
    }
}

执行上面的代码将为您提供以下结果:

book.getTitle() = The Ruby Programming Language
book.getAuthor() = David Flanagan & Yukihiro Matsumoto