6.3 通过数据的懒惰检索实现优化

有时我们可能想要优化对数据的集合(比如来自于数据库)的检索。如果这些集合确实要被使用,才会被检索。

  1. 实际上,这可以被应用到任何一块数据。这种场景的最普遍案例是给出集合在内存中的大小,遍历检索数据。

为此,Thymeleaf提供了一种机制,来懒惰加载上下文变量。实现了ILazyContextVariable接口的上下文变量————最有可能的是扩展了它的LazyContextVariable默认实现,将会在执行的时候被解析。比如:

  1. context.setVariable(
  2. "users",
  3. new LazyContextVariable<List<User>>() {
  4. @Override
  5. protected List<User> loadValue() {
  6. return databaseRepository.findAllUsers();
  7. }
  8. });

即使没有关于此变量的惰性的知识,也可以使用它。在如下代码里:

  1. <ul>
  2. <li th:each="u : ${users}" th:text="${u.name}">user name</li>
  3. </ul>

但是同时,如果下面代码里的condition的值为false,那么上面的代码不会被初始化(它的loadValue()方法不会被调用)。

  1. <ul th:if="${condition}">
  2. <li th:each="u : ${users}" th:text="${u.name}">user name</li>
  3. </ul>