org.thymeleaf.context.LazyContextVariable Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of thymeleaf Show documentation
Show all versions of thymeleaf Show documentation
Modern server-side Java template engine for both web and standalone environments
/*
* =============================================================================
*
* Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package org.thymeleaf.context;
/**
*
* Basic abstract implementation for the {@link ILazyContextVariable} interface.
*
*
* By extending this class instead of directly implementing the {@link ILazyContextVariable} interface,
* users can make sure that their variables will be initialized only once (per template execution). Once its
* inner abstract {@link #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();
* }
* });
*
*
* @param the type of the value being returned by this variable
*
* @author Daniel Fernández
*
* @since 3.0.0
*
*/
public abstract class LazyContextVariable implements ILazyContextVariable {
private volatile boolean initialized = false;
private T value;
protected LazyContextVariable() {
super();
}
public final T getValue() {
if (!this.initialized) {
synchronized (this) {
if (!this.initialized) {
this.value = loadValue();
this.initialized = true;
}
}
}
return this.value;
}
protected abstract T loadValue();
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy