Class LazyContextVariable<T>

  • Type Parameters:
    T - the type of the value being returned by this variable
    All Implemented Interfaces:
    ILazyContextVariable<T>

    public abstract class LazyContextVariable<T>
    extends java.lang.Object
    implements ILazyContextVariable<T>

    Basic abstract implementation for the ILazyContextVariable interface.

    By extending this class instead of directly implementing the ILazyContextVariable interface, users can make sure that their variables will be initialized only once (per template execution). Once its inner abstract loadValue() method is called --which implementation has to be provided by the user--, objects of this class will cache the results of such load and return these results every time the variable value is accessed.

    An example:

    
     context.setVariable(
         "users",
         new LazyContextVariable<List<User>>() {
             @Override
             protected List<User> loadValue() {
                 return databaseRepository.findAllUsers();
             }
         });
     
    Since:
    3.0.0
    • Field Summary

      Fields 
      Modifier and Type Field Description
      private boolean initialized  
      private T value  
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      protected LazyContextVariable()  
    • Method Summary

      All Methods Instance Methods Abstract Methods Concrete Methods 
      Modifier and Type Method Description
      T getValue()
      Lazily resolve the value.
      protected abstract T loadValue()
      Perform the actual resolution of the variable's value.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • initialized

        private volatile boolean initialized
      • value

        private T value
    • Constructor Detail

      • LazyContextVariable

        protected LazyContextVariable()
    • Method Detail

      • getValue

        public final T getValue()

        Lazily resolve the value.

        This will be transparently called by the Thymeleaf engine at template rendering time when an object of this class is resolved in a Thymeleaf expression.

        Note lazy variables will be resolved just once, and their resolved values will be reused as many times as they appear in the template.

        Specified by:
        getValue in interface ILazyContextVariable<T>
        Returns:
        the resolved value.
      • loadValue

        protected abstract T loadValue()

        Perform the actual resolution of the variable's value.

        This method will be called only once, the first time this variable is resolved.

        Returns:
        the resolved value.