6.3 通过数据的懒惰检索实现优化
有时我们可能想要优化对数据的集合(比如来自于数据库)的检索。如果这些集合确实要被使用,才会被检索。
实际上,这可以被应用到任何一块数据。这种场景的最普遍案例是给出集合在内存中的大小,遍历检索数据。
为此,Thymeleaf提供了一种机制,来懒惰加载上下文变量。实现了ILazyContextVariable
接口的上下文变量————最有可能的是扩展了它的LazyContextVariable
默认实现,将会在执行的时候被解析。比如:
context.setVariable(
"users",
new LazyContextVariable<List<User>>() {
@Override
protected List<User> loadValue() {
return databaseRepository.findAllUsers();
}
});
即使没有关于此变量的惰性的知识,也可以使用它。在如下代码里:
<ul>
<li th:each="u : ${users}" th:text="${u.name}">user name</li>
</ul>
但是同时,如果下面代码里的condition
的值为false
,那么上面的代码不会被初始化(它的loadValue()
方法不会被调用)。
<ul th:if="${condition}">
<li th:each="u : ${users}" th:text="${u.name}">user name</li>
</ul>