在此示例中,您将学习如何创建集合对象的投影。使用投影,我们可以创建一个仅具有原始集合中特定属性的新集合。
举例来说,Book我们不希望返回对象的集合,而只希望获得书名。为此,我们可以使用Spring EL投影运算符。此运算符的符号用法是![]。
让我们开始创建Spring配置文件:
<?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" p:pages="450"/> <bean p:title="User Stories Applied" p:author="Mike Cohen" p:pages="268"/> <bean p:title="Learning Android" p:author="Marco Gargenta" p:pages="245"/> <bean p:title="The Ruby Programming Language" p:author="David Flanagan & Yukihiro Matsumoto" p:pages="250"/> <bean p:title="Einstein" p:author="Walter Isaacson" p:pages="1000"/> </util:list> <bean id="library"> <property name="bookTitles" value="#{books.![title]}"/> </bean> </beans>
这是BookandLibrary类的定义。为了简化代码段,删除了getter和setter方法。
package org.nhooo.example.spring.el; public class Book { private Long id; private String title; private String author; private String type; private int pages; // Getters & Setters }
package org.nhooo.example.spring.el; import java.util.List; public class Library { private List<Book> books; private List<String> bookTitles; // Getters & Setters }
现在,让我们谈谈上面的Spring配置。配置是通过使用来创建“书籍”集合的开始<util:elements>。使用投影运算符的部分是配置的这一部分:
<bean id="library"> <property name="bookTitles" value="#{books.![title]}"/> </bean>
bean上面的元素创建一个library类型为的bean org.nhooo.example.spring.model.Library。我们为bean的bookTitles属性分配值,这些值是+ books +集合的投影,其中我们只接受书名。![projectionExpression]是投影运算符的语法。
下面的代码段将演示并运行我们的配置文件并打印出结果:
package org.nhooo.example.spring.el; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpELProjectionExample { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spel-projection.xml"); Library library = context.getBean("library", Library.class); for (String title : library.getBookTitles()) { System.out.println("title = " + title); } } }
结果如下:
title = Essential C# 4.0 title = User Stories Applied title = Learning Android title = The Ruby Programming Language title = Einstein