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 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
    Author:
    Daniel Fernández
    • 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.