使用Spring Expression Language(SpEL),我们可以根据一些条件过滤集合。我们还可以通过仅从集合对象中收集特定属性来创建集合的投影。
现在您知道您具有SpEL的两个良好功能,这些功能在处理集合对象操作时确实非常强大。但是您想知道如何在一个表达式中结合使用这些过滤器和投影。您可以在Spring EL中做到这一点吗?答案是肯定的!您可以将它们组合成一个表达式。让我们看下面的例子。
我们将使用与先前示例相同的配置:
<?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.?[pages gt 250].![title]}"/>
</bean>
</beans>在上面的配置中,当我们定义librarybean时,我们bookTitles使用过滤和投影运算符设置其属性。首先,我们只读取250页以上的书,然后创建仅包含书名的投影。因此,此表达式使我们拥有一本拥有250页以上的书的所有书名。
为了使示例在此处再次完整,请参见Book和Library类的定义。
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
}主类运行配置文件:
package org.nhooo.example.spring.el;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpELFilterProjectionExample {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spel-filter-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 = Einstein