Create spring-boot-freemarker module
This commit is contained in:
committed by
Phillip Webb
parent
b1ddb574d6
commit
5c948ab96b
25
spring-boot-project/spring-boot-freemarker/build.gradle
Normal file
25
spring-boot-project/spring-boot-freemarker/build.gradle
Normal file
@@ -0,0 +1,25 @@
|
||||
plugins {
|
||||
id "java-library"
|
||||
id "org.springframework.boot.auto-configuration"
|
||||
id "org.springframework.boot.configuration-properties"
|
||||
id "org.springframework.boot.deployed"
|
||||
id "org.springframework.boot.optional-dependencies"
|
||||
}
|
||||
|
||||
description = "Spring Boot Freemarker"
|
||||
|
||||
dependencies {
|
||||
api(project(":spring-boot-project:spring-boot"))
|
||||
api("org.freemarker:freemarker")
|
||||
api("org.springframework:spring-context-support")
|
||||
|
||||
optional(project(":spring-boot-project:spring-boot-autoconfigure"))
|
||||
optional("org.springframework:spring-webmvc")
|
||||
optional("org.springframework:spring-webflux")
|
||||
optional("jakarta.servlet:jakarta.servlet-api")
|
||||
|
||||
testImplementation(project(":spring-boot-project:spring-boot-test"))
|
||||
testImplementation(project(":spring-boot-project:spring-boot-tools:spring-boot-test-support"))
|
||||
|
||||
testRuntimeOnly("ch.qos.logback:logback-classic")
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
|
||||
|
||||
/**
|
||||
* Base class for shared FreeMarker configuration.
|
||||
*
|
||||
* @author Brian Clozel
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
abstract class AbstractFreeMarkerConfiguration {
|
||||
|
||||
private final FreeMarkerProperties properties;
|
||||
|
||||
private final List<FreeMarkerVariablesCustomizer> variablesCustomizers;
|
||||
|
||||
protected AbstractFreeMarkerConfiguration(FreeMarkerProperties properties,
|
||||
ObjectProvider<FreeMarkerVariablesCustomizer> variablesCustomizers) {
|
||||
this.properties = properties;
|
||||
this.variablesCustomizers = variablesCustomizers.orderedStream().toList();
|
||||
}
|
||||
|
||||
protected final FreeMarkerProperties getProperties() {
|
||||
return this.properties;
|
||||
}
|
||||
|
||||
protected void applyProperties(FreeMarkerConfigurationFactory factory) {
|
||||
factory.setTemplateLoaderPaths(this.properties.getTemplateLoaderPath());
|
||||
factory.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess());
|
||||
factory.setDefaultEncoding(this.properties.getCharsetName());
|
||||
factory.setFreemarkerSettings(createFreeMarkerSettings());
|
||||
factory.setFreemarkerVariables(createFreeMarkerVariables());
|
||||
}
|
||||
|
||||
private Properties createFreeMarkerSettings() {
|
||||
Properties settings = new Properties();
|
||||
settings.put("recognize_standard_file_extensions", "true");
|
||||
settings.putAll(this.properties.getSettings());
|
||||
return settings;
|
||||
}
|
||||
|
||||
private Map<String, Object> createFreeMarkerVariables() {
|
||||
Map<String, Object> variables = new HashMap<>();
|
||||
for (FreeMarkerVariablesCustomizer customizer : this.variablesCustomizers) {
|
||||
customizer.customizeFreeMarkerVariables(variables);
|
||||
}
|
||||
return variables;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.template.TemplateLocation;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
|
||||
|
||||
/**
|
||||
* {@link EnableAutoConfiguration Auto-configuration} for FreeMarker.
|
||||
*
|
||||
* @author Andy Wilkinson
|
||||
* @author Dave Syer
|
||||
* @author Kazuki Shimizu
|
||||
* @since 4.0.0
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@ConditionalOnClass({ freemarker.template.Configuration.class, FreeMarkerConfigurationFactory.class })
|
||||
@EnableConfigurationProperties(FreeMarkerProperties.class)
|
||||
@Import({ FreeMarkerServletWebConfiguration.class, FreeMarkerReactiveWebConfiguration.class,
|
||||
FreeMarkerNonWebConfiguration.class })
|
||||
public class FreeMarkerAutoConfiguration {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(FreeMarkerAutoConfiguration.class);
|
||||
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
private final FreeMarkerProperties properties;
|
||||
|
||||
public FreeMarkerAutoConfiguration(ApplicationContext applicationContext, FreeMarkerProperties properties) {
|
||||
this.applicationContext = applicationContext;
|
||||
this.properties = properties;
|
||||
checkTemplateLocationExists();
|
||||
}
|
||||
|
||||
public void checkTemplateLocationExists() {
|
||||
if (logger.isWarnEnabled() && this.properties.isCheckTemplateLocation()) {
|
||||
List<TemplateLocation> locations = getLocations();
|
||||
if (locations.stream().noneMatch(this::locationExists)) {
|
||||
String suffix = (locations.size() == 1) ? "" : "s";
|
||||
logger.warn("Cannot find template location" + suffix + ": " + locations
|
||||
+ " (please add some templates, " + "check your FreeMarker configuration, or set "
|
||||
+ "spring.freemarker.check-template-location=false)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<TemplateLocation> getLocations() {
|
||||
List<TemplateLocation> locations = new ArrayList<>();
|
||||
for (String templateLoaderPath : this.properties.getTemplateLoaderPath()) {
|
||||
TemplateLocation location = new TemplateLocation(templateLoaderPath);
|
||||
locations.add(location);
|
||||
}
|
||||
return locations;
|
||||
}
|
||||
|
||||
private boolean locationExists(TemplateLocation location) {
|
||||
return location.exists(this.applicationContext);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
|
||||
|
||||
/**
|
||||
* Configuration for FreeMarker when used in a non-web context.
|
||||
*
|
||||
* @author Brian Clozel
|
||||
* @author Andy Wilkinson
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnNotWebApplication
|
||||
class FreeMarkerNonWebConfiguration extends AbstractFreeMarkerConfiguration {
|
||||
|
||||
FreeMarkerNonWebConfiguration(FreeMarkerProperties properties,
|
||||
ObjectProvider<FreeMarkerVariablesCustomizer> variablesCustomizers) {
|
||||
super(properties, variablesCustomizers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FreeMarkerConfigurationFactoryBean freeMarkerConfiguration() {
|
||||
FreeMarkerConfigurationFactoryBean freeMarkerFactoryBean = new FreeMarkerConfigurationFactoryBean();
|
||||
applyProperties(freeMarkerFactoryBean);
|
||||
return freeMarkerFactoryBean;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.MimeType;
|
||||
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
|
||||
|
||||
/**
|
||||
* {@link ConfigurationProperties @ConfigurationProperties} for configuring FreeMarker.
|
||||
*
|
||||
* @author Dave Syer
|
||||
* @author Andy Wilkinson
|
||||
* @since 4.0.0
|
||||
*/
|
||||
@ConfigurationProperties("spring.freemarker")
|
||||
public class FreeMarkerProperties {
|
||||
|
||||
public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
|
||||
|
||||
public static final String DEFAULT_PREFIX = "";
|
||||
|
||||
public static final String DEFAULT_SUFFIX = ".ftlh";
|
||||
|
||||
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
|
||||
|
||||
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
|
||||
|
||||
/**
|
||||
* Whether to enable MVC view resolution for this technology.
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
|
||||
/**
|
||||
* Whether to enable template caching.
|
||||
*/
|
||||
private boolean cache;
|
||||
|
||||
/**
|
||||
* Content-Type value.
|
||||
*/
|
||||
private MimeType contentType = DEFAULT_CONTENT_TYPE;
|
||||
|
||||
/**
|
||||
* Template encoding.
|
||||
*/
|
||||
private Charset charset = DEFAULT_CHARSET;
|
||||
|
||||
/**
|
||||
* View names that can be resolved.
|
||||
*/
|
||||
private String[] viewNames;
|
||||
|
||||
/**
|
||||
* Whether to check that the templates location exists.
|
||||
*/
|
||||
private boolean checkTemplateLocation = true;
|
||||
|
||||
/**
|
||||
* Prefix that gets prepended to view names when building a URL.
|
||||
*/
|
||||
private String prefix = DEFAULT_PREFIX;
|
||||
|
||||
/**
|
||||
* Suffix that gets appended to view names when building a URL.
|
||||
*/
|
||||
private String suffix = DEFAULT_SUFFIX;
|
||||
|
||||
/**
|
||||
* Name of the RequestContext attribute for all views.
|
||||
*/
|
||||
private String requestContextAttribute;
|
||||
|
||||
/**
|
||||
* Whether all request attributes should be added to the model prior to merging with
|
||||
* the template.
|
||||
*/
|
||||
private boolean exposeRequestAttributes = false;
|
||||
|
||||
/**
|
||||
* Whether all HttpSession attributes should be added to the model prior to merging
|
||||
* with the template.
|
||||
*/
|
||||
private boolean exposeSessionAttributes = false;
|
||||
|
||||
/**
|
||||
* Whether HttpServletRequest attributes are allowed to override (hide) controller
|
||||
* generated model attributes of the same name.
|
||||
*/
|
||||
private boolean allowRequestOverride = false;
|
||||
|
||||
/**
|
||||
* Whether to expose a RequestContext for use by Spring's macro library, under the
|
||||
* name "springMacroRequestContext".
|
||||
*/
|
||||
private boolean exposeSpringMacroHelpers = true;
|
||||
|
||||
/**
|
||||
* Whether HttpSession attributes are allowed to override (hide) controller generated
|
||||
* model attributes of the same name.
|
||||
*/
|
||||
private boolean allowSessionOverride = false;
|
||||
|
||||
/**
|
||||
* Well-known FreeMarker keys which are passed to FreeMarker's Configuration.
|
||||
*/
|
||||
private Map<String, String> settings = new HashMap<>();
|
||||
|
||||
/**
|
||||
* List of template paths.
|
||||
*/
|
||||
private String[] templateLoaderPath = new String[] { DEFAULT_TEMPLATE_LOADER_PATH };
|
||||
|
||||
/**
|
||||
* Whether to prefer file system access for template loading to enable hot detection
|
||||
* of template changes. When a template path is detected as a directory, templates are
|
||||
* loaded from the directory only and other matching classpath locations will not be
|
||||
* considered.
|
||||
*/
|
||||
private boolean preferFileSystemAccess;
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
public void setCheckTemplateLocation(boolean checkTemplateLocation) {
|
||||
this.checkTemplateLocation = checkTemplateLocation;
|
||||
}
|
||||
|
||||
public boolean isCheckTemplateLocation() {
|
||||
return this.checkTemplateLocation;
|
||||
}
|
||||
|
||||
public String[] getViewNames() {
|
||||
return this.viewNames;
|
||||
}
|
||||
|
||||
public void setViewNames(String[] viewNames) {
|
||||
this.viewNames = viewNames;
|
||||
}
|
||||
|
||||
public boolean isCache() {
|
||||
return this.cache;
|
||||
}
|
||||
|
||||
public void setCache(boolean cache) {
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
public MimeType getContentType() {
|
||||
if (this.contentType.getCharset() == null) {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("charset", this.charset.name());
|
||||
parameters.putAll(this.contentType.getParameters());
|
||||
return new MimeType(this.contentType, parameters);
|
||||
}
|
||||
return this.contentType;
|
||||
}
|
||||
|
||||
public void setContentType(MimeType contentType) {
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
public Charset getCharset() {
|
||||
return this.charset;
|
||||
}
|
||||
|
||||
public String getCharsetName() {
|
||||
return (this.charset != null) ? this.charset.name() : null;
|
||||
}
|
||||
|
||||
public void setCharset(Charset charset) {
|
||||
this.charset = charset;
|
||||
}
|
||||
|
||||
public Map<String, String> getSettings() {
|
||||
return this.settings;
|
||||
}
|
||||
|
||||
public void setSettings(Map<String, String> settings) {
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
public String[] getTemplateLoaderPath() {
|
||||
return this.templateLoaderPath;
|
||||
}
|
||||
|
||||
public void setTemplateLoaderPath(String... templateLoaderPaths) {
|
||||
this.templateLoaderPath = templateLoaderPaths;
|
||||
}
|
||||
|
||||
public boolean isPreferFileSystemAccess() {
|
||||
return this.preferFileSystemAccess;
|
||||
}
|
||||
|
||||
public void setPreferFileSystemAccess(boolean preferFileSystemAccess) {
|
||||
this.preferFileSystemAccess = preferFileSystemAccess;
|
||||
}
|
||||
|
||||
public String getPrefix() {
|
||||
return this.prefix;
|
||||
}
|
||||
|
||||
public void setPrefix(String prefix) {
|
||||
this.prefix = prefix;
|
||||
}
|
||||
|
||||
public String getSuffix() {
|
||||
return this.suffix;
|
||||
}
|
||||
|
||||
public void setSuffix(String suffix) {
|
||||
this.suffix = suffix;
|
||||
}
|
||||
|
||||
public String getRequestContextAttribute() {
|
||||
return this.requestContextAttribute;
|
||||
}
|
||||
|
||||
public void setRequestContextAttribute(String requestContextAttribute) {
|
||||
this.requestContextAttribute = requestContextAttribute;
|
||||
}
|
||||
|
||||
public boolean isExposeRequestAttributes() {
|
||||
return this.exposeRequestAttributes;
|
||||
}
|
||||
|
||||
public void setExposeRequestAttributes(boolean exposeRequestAttributes) {
|
||||
this.exposeRequestAttributes = exposeRequestAttributes;
|
||||
}
|
||||
|
||||
public boolean isExposeSessionAttributes() {
|
||||
return this.exposeSessionAttributes;
|
||||
}
|
||||
|
||||
public void setExposeSessionAttributes(boolean exposeSessionAttributes) {
|
||||
this.exposeSessionAttributes = exposeSessionAttributes;
|
||||
}
|
||||
|
||||
public boolean isAllowRequestOverride() {
|
||||
return this.allowRequestOverride;
|
||||
}
|
||||
|
||||
public void setAllowRequestOverride(boolean allowRequestOverride) {
|
||||
this.allowRequestOverride = allowRequestOverride;
|
||||
}
|
||||
|
||||
public boolean isAllowSessionOverride() {
|
||||
return this.allowSessionOverride;
|
||||
}
|
||||
|
||||
public void setAllowSessionOverride(boolean allowSessionOverride) {
|
||||
this.allowSessionOverride = allowSessionOverride;
|
||||
}
|
||||
|
||||
public boolean isExposeSpringMacroHelpers() {
|
||||
return this.exposeSpringMacroHelpers;
|
||||
}
|
||||
|
||||
public void setExposeSpringMacroHelpers(boolean exposeSpringMacroHelpers) {
|
||||
this.exposeSpringMacroHelpers = exposeSpringMacroHelpers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the given properties to a {@link AbstractTemplateViewResolver}. Use Object in
|
||||
* signature to avoid runtime dependency on MVC, which means that the template engine
|
||||
* can be used in a non-web application.
|
||||
* @param viewResolver the resolver to apply the properties to.
|
||||
*/
|
||||
public void applyToMvcViewResolver(Object viewResolver) {
|
||||
Assert.isInstanceOf(AbstractTemplateViewResolver.class, viewResolver,
|
||||
() -> "ViewResolver is not an instance of AbstractTemplateViewResolver :" + viewResolver);
|
||||
AbstractTemplateViewResolver resolver = (AbstractTemplateViewResolver) viewResolver;
|
||||
resolver.setPrefix(getPrefix());
|
||||
resolver.setSuffix(getSuffix());
|
||||
resolver.setCache(isCache());
|
||||
if (getContentType() != null) {
|
||||
resolver.setContentType(getContentType().toString());
|
||||
}
|
||||
resolver.setViewNames(getViewNames());
|
||||
resolver.setExposeRequestAttributes(isExposeRequestAttributes());
|
||||
resolver.setAllowRequestOverride(isAllowRequestOverride());
|
||||
resolver.setAllowSessionOverride(isAllowSessionOverride());
|
||||
resolver.setExposeSessionAttributes(isExposeSessionAttributes());
|
||||
resolver.setExposeSpringMacroHelpers(isExposeSpringMacroHelpers());
|
||||
resolver.setRequestContextAttribute(getRequestContextAttribute());
|
||||
// The resolver usually acts as a fallback resolver (e.g. like a
|
||||
// InternalResourceViewResolver) so it needs to have low precedence
|
||||
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfig;
|
||||
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;
|
||||
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver;
|
||||
|
||||
/**
|
||||
* Configuration for FreeMarker when used in a reactive web context.
|
||||
*
|
||||
* @author Brian Clozel
|
||||
* @author Andy Wilkinson
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
|
||||
@ConditionalOnClass(FreeMarkerConfigurer.class)
|
||||
@AutoConfigureAfter(name = "org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration")
|
||||
class FreeMarkerReactiveWebConfiguration extends AbstractFreeMarkerConfiguration {
|
||||
|
||||
FreeMarkerReactiveWebConfiguration(FreeMarkerProperties properties,
|
||||
ObjectProvider<FreeMarkerVariablesCustomizer> variablesCustomizers) {
|
||||
super(properties, variablesCustomizers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(FreeMarkerConfig.class)
|
||||
FreeMarkerConfigurer freeMarkerConfigurer() {
|
||||
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
|
||||
applyProperties(configurer);
|
||||
return configurer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
freemarker.template.Configuration freeMarkerConfiguration(FreeMarkerConfig configurer) {
|
||||
return configurer.getConfiguration();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(name = "freeMarkerViewResolver")
|
||||
@ConditionalOnBooleanProperty(name = "spring.freemarker.enabled", matchIfMissing = true)
|
||||
FreeMarkerViewResolver freeMarkerViewResolver() {
|
||||
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
|
||||
resolver.setPrefix(getProperties().getPrefix());
|
||||
resolver.setSuffix(getProperties().getSuffix());
|
||||
resolver.setRequestContextAttribute(getProperties().getRequestContextAttribute());
|
||||
resolver.setViewNames(getProperties().getViewNames());
|
||||
return resolver;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.Servlet;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingFilterBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.boot.autoconfigure.web.ConditionalOnEnabledResourceChain;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
|
||||
|
||||
/**
|
||||
* Configuration for FreeMarker when used in a servlet web context.
|
||||
*
|
||||
* @author Brian Clozel
|
||||
* @author Andy Wilkinson
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
|
||||
@ConditionalOnClass({ Servlet.class, FreeMarkerConfigurer.class })
|
||||
@AutoConfigureAfter(name = "org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration")
|
||||
class FreeMarkerServletWebConfiguration extends AbstractFreeMarkerConfiguration {
|
||||
|
||||
protected FreeMarkerServletWebConfiguration(FreeMarkerProperties properties,
|
||||
ObjectProvider<FreeMarkerVariablesCustomizer> variablesCustomizers) {
|
||||
super(properties, variablesCustomizers);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(FreeMarkerConfig.class)
|
||||
FreeMarkerConfigurer freeMarkerConfigurer() {
|
||||
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
|
||||
applyProperties(configurer);
|
||||
return configurer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
freemarker.template.Configuration freeMarkerConfiguration(FreeMarkerConfig configurer) {
|
||||
return configurer.getConfiguration();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(name = "freeMarkerViewResolver")
|
||||
@ConditionalOnBooleanProperty(name = "spring.freemarker.enabled", matchIfMissing = true)
|
||||
FreeMarkerViewResolver freeMarkerViewResolver() {
|
||||
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
|
||||
getProperties().applyToMvcViewResolver(resolver);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnEnabledResourceChain
|
||||
@ConditionalOnMissingFilterBean
|
||||
FilterRegistrationBean<ResourceUrlEncodingFilter> resourceUrlEncodingFilter() {
|
||||
FilterRegistrationBean<ResourceUrlEncodingFilter> registration = new FilterRegistrationBean<>(
|
||||
new ResourceUrlEncodingFilter());
|
||||
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ERROR);
|
||||
return registration;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.aot.hint.RuntimeHintsRegistrar;
|
||||
import org.springframework.boot.autoconfigure.template.PathBasedTemplateAvailabilityProvider;
|
||||
import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider;
|
||||
import org.springframework.boot.context.properties.bind.BindableRuntimeHintsRegistrar;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* {@link TemplateAvailabilityProvider} that provides availability information for
|
||||
* FreeMarker view templates.
|
||||
*
|
||||
* @author Andy Wilkinson
|
||||
* @since 4.0.0
|
||||
*/
|
||||
public class FreeMarkerTemplateAvailabilityProvider extends PathBasedTemplateAvailabilityProvider {
|
||||
|
||||
private static final String REQUIRED_CLASS_NAME = "freemarker.template.Configuration";
|
||||
|
||||
public FreeMarkerTemplateAvailabilityProvider() {
|
||||
super(REQUIRED_CLASS_NAME, FreeMarkerTemplateAvailabilityProperties.class, "spring.freemarker");
|
||||
}
|
||||
|
||||
protected static final class FreeMarkerTemplateAvailabilityProperties extends TemplateAvailabilityProperties {
|
||||
|
||||
private List<String> templateLoaderPath = new ArrayList<>(
|
||||
Arrays.asList(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH));
|
||||
|
||||
FreeMarkerTemplateAvailabilityProperties() {
|
||||
super(FreeMarkerProperties.DEFAULT_PREFIX, FreeMarkerProperties.DEFAULT_SUFFIX);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<String> getLoaderPath() {
|
||||
return this.templateLoaderPath;
|
||||
}
|
||||
|
||||
public List<String> getTemplateLoaderPath() {
|
||||
return this.templateLoaderPath;
|
||||
}
|
||||
|
||||
public void setTemplateLoaderPath(List<String> templateLoaderPath) {
|
||||
this.templateLoaderPath = templateLoaderPath;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class FreeMarkerTemplateAvailabilityRuntimeHints implements RuntimeHintsRegistrar {
|
||||
|
||||
@Override
|
||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||
if (ClassUtils.isPresent(REQUIRED_CLASS_NAME, classLoader)) {
|
||||
BindableRuntimeHintsRegistrar.forTypes(FreeMarkerTemplateAvailabilityProperties.class)
|
||||
.registerHints(hints, classLoader);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import freemarker.template.Configuration;
|
||||
|
||||
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
|
||||
|
||||
/**
|
||||
* Callback interface that can be implemented by beans wishing to customize the FreeMarker
|
||||
* variables used as {@link Configuration#getSharedVariableNames() shared variables}
|
||||
* before it is used by an auto-configured {@link FreeMarkerConfigurationFactory}.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
* @since 4.0.0
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface FreeMarkerVariablesCustomizer {
|
||||
|
||||
/**
|
||||
* Customize the {@code variables} to be set as well-known FreeMarker objects.
|
||||
* @param variables the variables to customize
|
||||
* @see FreeMarkerConfigurationFactory#setFreemarkerVariables(Map)
|
||||
*/
|
||||
void customizeFreeMarkerVariables(Map<String, Object> variables);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2012-2019 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Auto-configuration for FreeMarker.
|
||||
*/
|
||||
package org.springframework.boot.freemarker.autoconfigure;
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"groups": [],
|
||||
"properties": [
|
||||
{
|
||||
"name": "spring.freemarker.allow-request-override",
|
||||
"description": "Whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name. Only supported with Spring MVC."
|
||||
},
|
||||
{
|
||||
"name": "spring.freemarker.allow-session-override",
|
||||
"description": "Whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name. Only supported with Spring MVC."
|
||||
},
|
||||
{
|
||||
"name": "spring.freemarker.cache",
|
||||
"description": "Whether to enable template caching. Only supported with Spring MVC."
|
||||
},
|
||||
{
|
||||
"name": "spring.freemarker.content-type",
|
||||
"description": "Content-Type value. Only supported with Spring MVC."
|
||||
},
|
||||
{
|
||||
"name": "spring.freemarker.expose-request-attributes",
|
||||
"description": "Whether all request attributes should be added to the model prior to merging with the template. Only supported with Spring MVC."
|
||||
},
|
||||
{
|
||||
"name": "spring.freemarker.expose-session-attributes",
|
||||
"description": "Whether all HttpSession attributes should be added to the model prior to merging with the template. Only supported with Spring MVC."
|
||||
},
|
||||
{
|
||||
"name": "spring.freemarker.expose-spring-macro-helpers",
|
||||
"description": "Whether to expose a RequestContext for use by Spring's macro library, under the name \"springMacroRequestContext\". Only supported with Spring MVC."
|
||||
},
|
||||
{
|
||||
"name": "spring.freemarker.prefix",
|
||||
"defaultValue": ""
|
||||
},
|
||||
{
|
||||
"name": "spring.freemarker.suffix",
|
||||
"defaultValue": ".ftlh"
|
||||
}
|
||||
],
|
||||
"hints": [],
|
||||
"ignored": {
|
||||
"properties": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Template Availability Providers
|
||||
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
|
||||
org.springframework.boot.freemarker.autoconfigure.FreeMarkerTemplateAvailabilityProvider
|
||||
@@ -0,0 +1,2 @@
|
||||
org.springframework.aot.hint.RuntimeHintsRegistrar=\
|
||||
org.springframework.boot.freemarker.autoconfigure.FreeMarkerTemplateAvailabilityProvider$FreeMarkerTemplateAvailabilityRuntimeHints
|
||||
@@ -0,0 +1 @@
|
||||
org.springframework.boot.freemarker.autoconfigure.FreeMarkerAutoConfiguration
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.time.Duration;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
|
||||
import org.springframework.boot.testsupport.classpath.resources.WithResource;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import org.springframework.mock.web.server.MockServerWebExchange;
|
||||
import org.springframework.web.reactive.result.view.View;
|
||||
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfig;
|
||||
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;
|
||||
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Tests for {@link FreeMarkerAutoConfiguration} Reactive support.
|
||||
*
|
||||
* @author Brian Clozel
|
||||
*/
|
||||
class FreeMarkerAutoConfigurationReactiveIntegrationTests {
|
||||
|
||||
private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class));
|
||||
|
||||
@BeforeEach
|
||||
@AfterEach
|
||||
void clearReactorSchedulers() {
|
||||
Schedulers.shutdownNow();
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultConfiguration() {
|
||||
this.contextRunner.run((context) -> {
|
||||
assertThat(context.getBean(FreeMarkerViewResolver.class)).isNotNull();
|
||||
assertThat(context.getBean(FreeMarkerConfigurer.class)).isNotNull();
|
||||
assertThat(context.getBean(FreeMarkerConfig.class)).isNotNull();
|
||||
assertThat(context.getBean(freemarker.template.Configuration.class)).isNotNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/home.ftlh", content = "home")
|
||||
void defaultViewResolution() {
|
||||
this.contextRunner.run((context) -> {
|
||||
MockServerWebExchange exchange = render(context, "home");
|
||||
String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30));
|
||||
assertThat(result).contains("home");
|
||||
assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/prefix/prefixed.ftlh", content = "prefixed")
|
||||
void customPrefix() {
|
||||
this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/").run((context) -> {
|
||||
MockServerWebExchange exchange = render(context, "prefixed");
|
||||
String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30));
|
||||
assertThat(result).contains("prefixed");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/suffixed.freemarker", content = "suffixed")
|
||||
void customSuffix() {
|
||||
this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker").run((context) -> {
|
||||
MockServerWebExchange exchange = render(context, "suffixed");
|
||||
String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30));
|
||||
assertThat(result).contains("suffixed");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "custom-templates/custom.ftlh", content = "custom")
|
||||
void customTemplateLoaderPath() {
|
||||
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/custom-templates/")
|
||||
.run((context) -> {
|
||||
MockServerWebExchange exchange = render(context, "custom");
|
||||
String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30));
|
||||
assertThat(result).contains("custom");
|
||||
});
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Test
|
||||
void customFreeMarkerSettings() {
|
||||
this.contextRunner.withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope")
|
||||
.run((context) -> assertThat(
|
||||
context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format"))
|
||||
.isEqualTo("yup,nope"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/message.ftlh", content = "Message: ${greeting}")
|
||||
void renderTemplate() {
|
||||
this.contextRunner.withPropertyValues().run((context) -> {
|
||||
FreeMarkerConfigurer freemarker = context.getBean(FreeMarkerConfigurer.class);
|
||||
StringWriter writer = new StringWriter();
|
||||
freemarker.getConfiguration().getTemplate("message.ftlh").process(new DataModel(), writer);
|
||||
assertThat(writer.toString()).contains("Hello World");
|
||||
});
|
||||
}
|
||||
|
||||
private MockServerWebExchange render(ApplicationContext context, String viewName) {
|
||||
FreeMarkerViewResolver resolver = context.getBean(FreeMarkerViewResolver.class);
|
||||
Mono<View> view = resolver.resolveViewName(viewName, Locale.UK);
|
||||
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path"));
|
||||
view.flatMap((v) -> v.render(null, MediaType.TEXT_HTML, exchange)).block(Duration.ofSeconds(30));
|
||||
return exchange;
|
||||
}
|
||||
|
||||
public static class DataModel {
|
||||
|
||||
public String getGreeting() {
|
||||
return "Hello World";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
|
||||
import org.springframework.boot.test.util.TestPropertyValues;
|
||||
import org.springframework.boot.testsupport.classpath.resources.WithResource;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebApplicationContext;
|
||||
import org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.servlet.View;
|
||||
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
|
||||
import org.springframework.web.servlet.support.RequestContext;
|
||||
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Tests for {@link FreeMarkerAutoConfiguration} Servlet support.
|
||||
*
|
||||
* @author Andy Wilkinson
|
||||
* @author Kazuki Shimizu
|
||||
*/
|
||||
class FreeMarkerAutoConfigurationServletIntegrationTests {
|
||||
|
||||
private AnnotationConfigServletWebApplicationContext context;
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultConfiguration() {
|
||||
load();
|
||||
assertThat(this.context.getBean(FreeMarkerViewResolver.class)).isNotNull();
|
||||
assertThat(this.context.getBean(FreeMarkerConfigurer.class)).isNotNull();
|
||||
assertThat(this.context.getBean(FreeMarkerConfig.class)).isNotNull();
|
||||
assertThat(this.context.getBean(freemarker.template.Configuration.class)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/home.ftlh", content = "home")
|
||||
void defaultViewResolution() throws Exception {
|
||||
load();
|
||||
MockHttpServletResponse response = render("home");
|
||||
String result = response.getContentAsString();
|
||||
assertThat(result).contains("home");
|
||||
assertThat(response.getContentType()).isEqualTo("text/html;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/home.ftlh", content = "home")
|
||||
void customContentType() throws Exception {
|
||||
load("spring.freemarker.contentType:application/json");
|
||||
MockHttpServletResponse response = render("home");
|
||||
String result = response.getContentAsString();
|
||||
assertThat(result).contains("home");
|
||||
assertThat(response.getContentType()).isEqualTo("application/json;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/prefix/prefixed.ftlh", content = "prefixed")
|
||||
void customPrefix() throws Exception {
|
||||
load("spring.freemarker.prefix:prefix/");
|
||||
MockHttpServletResponse response = render("prefixed");
|
||||
String result = response.getContentAsString();
|
||||
assertThat(result).contains("prefixed");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/suffixed.freemarker", content = "suffixed")
|
||||
void customSuffix() throws Exception {
|
||||
load("spring.freemarker.suffix:.freemarker");
|
||||
MockHttpServletResponse response = render("suffixed");
|
||||
String result = response.getContentAsString();
|
||||
assertThat(result).contains("suffixed");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "custom-templates/custom.ftlh", content = "custom")
|
||||
void customTemplateLoaderPath() throws Exception {
|
||||
load("spring.freemarker.templateLoaderPath:classpath:/custom-templates/");
|
||||
MockHttpServletResponse response = render("custom");
|
||||
String result = response.getContentAsString();
|
||||
assertThat(result).contains("custom");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableCache() {
|
||||
load("spring.freemarker.cache:false");
|
||||
assertThat(this.context.getBean(FreeMarkerViewResolver.class).getCacheLimit()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowSessionOverride() {
|
||||
load("spring.freemarker.allow-session-override:true");
|
||||
AbstractTemplateViewResolver viewResolver = this.context.getBean(FreeMarkerViewResolver.class);
|
||||
assertThat(viewResolver).hasFieldOrPropertyWithValue("allowSessionOverride", true);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@Test
|
||||
void customFreeMarkerSettings() {
|
||||
load("spring.freemarker.settings.boolean_format:yup,nope");
|
||||
assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format"))
|
||||
.isEqualTo("yup,nope");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/message.ftlh", content = "Message: ${greeting}")
|
||||
void renderTemplate() throws Exception {
|
||||
load();
|
||||
FreeMarkerConfigurer freemarker = this.context.getBean(FreeMarkerConfigurer.class);
|
||||
StringWriter writer = new StringWriter();
|
||||
freemarker.getConfiguration().getTemplate("message.ftlh").process(new DataModel(), writer);
|
||||
assertThat(writer.toString()).contains("Hello World");
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerResourceHandlingFilterDisabledByDefault() {
|
||||
load();
|
||||
assertThat(this.context.getBeansOfType(FilterRegistrationBean.class)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerResourceHandlingFilterOnlyIfResourceChainIsEnabled() {
|
||||
load("spring.web.resources.chain.enabled:true");
|
||||
FilterRegistrationBean<?> registration = this.context.getBean(FilterRegistrationBean.class);
|
||||
assertThat(registration.getFilter()).isInstanceOf(ResourceUrlEncodingFilter.class);
|
||||
assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes",
|
||||
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
void registerResourceHandlingFilterWithOtherRegistrationBean() {
|
||||
// gh-14897
|
||||
load(FilterRegistrationOtherConfiguration.class, "spring.web.resources.chain.enabled:true");
|
||||
Map<String, FilterRegistrationBean> beans = this.context.getBeansOfType(FilterRegistrationBean.class);
|
||||
assertThat(beans).hasSize(2);
|
||||
FilterRegistrationBean registration = beans.values()
|
||||
.stream()
|
||||
.filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter)
|
||||
.findFirst()
|
||||
.get();
|
||||
assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes",
|
||||
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
void registerResourceHandlingFilterWithResourceRegistrationBean() {
|
||||
// gh-14926
|
||||
load(FilterRegistrationResourceConfiguration.class, "spring.web.resources.chain.enabled:true");
|
||||
Map<String, FilterRegistrationBean> beans = this.context.getBeansOfType(FilterRegistrationBean.class);
|
||||
assertThat(beans).hasSize(1);
|
||||
FilterRegistrationBean registration = beans.values()
|
||||
.stream()
|
||||
.filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter)
|
||||
.findFirst()
|
||||
.get();
|
||||
assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.INCLUDE));
|
||||
}
|
||||
|
||||
private void load(String... env) {
|
||||
load(BaseConfiguration.class, env);
|
||||
}
|
||||
|
||||
private void load(Class<?> config, String... env) {
|
||||
this.context = new AnnotationConfigServletWebApplicationContext();
|
||||
this.context.setServletContext(new MockServletContext());
|
||||
TestPropertyValues.of(env).applyTo(this.context);
|
||||
this.context.register(config);
|
||||
this.context.refresh();
|
||||
}
|
||||
|
||||
private MockHttpServletResponse render(String viewName) throws Exception {
|
||||
FreeMarkerViewResolver resolver = this.context.getBean(FreeMarkerViewResolver.class);
|
||||
View view = resolver.resolveViewName(viewName, Locale.UK);
|
||||
assertThat(view).isNotNull();
|
||||
HttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
view.render(null, request, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ImportAutoConfiguration({ FreeMarkerAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class })
|
||||
static class BaseConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import(BaseConfiguration.class)
|
||||
static class FilterRegistrationResourceConfiguration {
|
||||
|
||||
@Bean
|
||||
FilterRegistrationBean<ResourceUrlEncodingFilter> filterRegistration() {
|
||||
FilterRegistrationBean<ResourceUrlEncodingFilter> bean = new FilterRegistrationBean<>(
|
||||
new ResourceUrlEncodingFilter());
|
||||
bean.setDispatcherTypes(EnumSet.of(DispatcherType.INCLUDE));
|
||||
return bean;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import(BaseConfiguration.class)
|
||||
static class FilterRegistrationOtherConfiguration {
|
||||
|
||||
@Bean
|
||||
FilterRegistrationBean<OrderedCharacterEncodingFilter> filterRegistration() {
|
||||
return new FilterRegistrationBean<>(new OrderedCharacterEncodingFilter());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class DataModel {
|
||||
|
||||
public String getGreeting() {
|
||||
return "Hello World";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.boot.test.system.CapturedOutput;
|
||||
import org.springframework.boot.test.system.OutputCaptureExtension;
|
||||
import org.springframework.boot.testsupport.classpath.resources.WithResource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.BDDMockito.then;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Tests for {@link FreeMarkerAutoConfiguration}.
|
||||
*
|
||||
* @author Andy Wilkinson
|
||||
* @author Kazuki Shimizu
|
||||
*/
|
||||
@ExtendWith(OutputCaptureExtension.class)
|
||||
class FreeMarkerAutoConfigurationTests {
|
||||
|
||||
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class));
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/message.ftlh", content = "Message: ${greeting}")
|
||||
void renderNonWebAppTemplate() {
|
||||
this.contextRunner.run((context) -> {
|
||||
freemarker.template.Configuration freemarker = context.getBean(freemarker.template.Configuration.class);
|
||||
StringWriter writer = new StringWriter();
|
||||
freemarker.getTemplate("message.ftlh").process(new DataModel(), writer);
|
||||
assertThat(writer.toString()).contains("Hello World");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonExistentTemplateLocation(CapturedOutput output) {
|
||||
this.contextRunner
|
||||
.withPropertyValues("spring.freemarker.templateLoaderPath:"
|
||||
+ "classpath:/does-not-exist/,classpath:/also-does-not-exist")
|
||||
.run((context) -> assertThat(output).contains("Cannot find template location"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyTemplateLocation(CapturedOutput output, @TempDir Path tempDir) {
|
||||
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:file:" + tempDir.toAbsolutePath())
|
||||
.run((context) -> assertThat(output).doesNotContain("Cannot find template location"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonExistentLocationAndEmptyLocation(CapturedOutput output, @TempDir Path tempDir) {
|
||||
this.contextRunner
|
||||
.withPropertyValues("spring.freemarker.templateLoaderPath:" + "classpath:/does-not-exist/,file:"
|
||||
+ tempDir.toAbsolutePath())
|
||||
.run((context) -> assertThat(output).doesNotContain("Cannot find template location"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void variableCustomizerShouldBeApplied() {
|
||||
FreeMarkerVariablesCustomizer customizer = mock(FreeMarkerVariablesCustomizer.class);
|
||||
this.contextRunner.withBean(FreeMarkerVariablesCustomizer.class, () -> customizer)
|
||||
.run((context) -> then(customizer).should().customizeFreeMarkerVariables(any()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void variableCustomizersShouldBeAppliedInOrder() {
|
||||
this.contextRunner.withUserConfiguration(VariablesCustomizersConfiguration.class).run((context) -> {
|
||||
assertThat(context).hasSingleBean(freemarker.template.Configuration.class);
|
||||
freemarker.template.Configuration configuration = context.getBean(freemarker.template.Configuration.class);
|
||||
assertThat(configuration.getSharedVariableNames()).contains("order", "one", "two");
|
||||
assertThat(configuration.getSharedVariable("order")).hasToString("5");
|
||||
});
|
||||
}
|
||||
|
||||
public static class DataModel {
|
||||
|
||||
public String getGreeting() {
|
||||
return "Hello World";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class VariablesCustomizersConfiguration {
|
||||
|
||||
@Bean
|
||||
@Order(5)
|
||||
FreeMarkerVariablesCustomizer variablesCustomizer() {
|
||||
return (variables) -> {
|
||||
variables.put("order", 5);
|
||||
variables.put("one", "one");
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(2)
|
||||
FreeMarkerVariablesCustomizer anotherVariablesCustomizer() {
|
||||
return (variables) -> {
|
||||
variables.put("order", 2);
|
||||
variables.put("two", "two");
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.util.MimeTypeUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Tests for {@link FreeMarkerProperties}.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
*/
|
||||
class FreeMarkerPropertiesTests {
|
||||
|
||||
@Test
|
||||
void defaultContentType() {
|
||||
assertThat(new FreeMarkerProperties().getContentType()).hasToString("text/html;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
void customContentTypeDefaultCharset() {
|
||||
FreeMarkerProperties properties = new FreeMarkerProperties();
|
||||
properties.setContentType(MimeTypeUtils.parseMimeType("text/plain"));
|
||||
assertThat(properties.getContentType()).hasToString("text/plain;charset=UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultContentTypeCustomCharset() {
|
||||
FreeMarkerProperties properties = new FreeMarkerProperties();
|
||||
properties.setCharset(StandardCharsets.UTF_16);
|
||||
assertThat(properties.getContentType()).hasToString("text/html;charset=UTF-16");
|
||||
}
|
||||
|
||||
@Test
|
||||
void customContentTypeCustomCharset() {
|
||||
FreeMarkerProperties properties = new FreeMarkerProperties();
|
||||
properties.setContentType(MimeTypeUtils.parseMimeType("text/plain"));
|
||||
properties.setCharset(StandardCharsets.UTF_16);
|
||||
assertThat(properties.getContentType()).hasToString("text/plain;charset=UTF-16");
|
||||
}
|
||||
|
||||
@Test
|
||||
void customContentTypeWithPropertyAndCustomCharset() {
|
||||
FreeMarkerProperties properties = new FreeMarkerProperties();
|
||||
properties.setContentType(MimeTypeUtils.parseMimeType("text/plain;foo=bar"));
|
||||
properties.setCharset(StandardCharsets.UTF_16);
|
||||
assertThat(properties.getContentType()).hasToString("text/plain;charset=UTF-16;foo=bar");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright 2012-2025 the original author or authors.
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* https://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.springframework.boot.freemarker.autoconfigure;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.aot.hint.RuntimeHintsRegistrar;
|
||||
import org.springframework.aot.hint.TypeHint;
|
||||
import org.springframework.beans.factory.aot.AotServices;
|
||||
import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider;
|
||||
import org.springframework.boot.freemarker.autoconfigure.FreeMarkerTemplateAvailabilityProvider.FreeMarkerTemplateAvailabilityProperties;
|
||||
import org.springframework.boot.freemarker.autoconfigure.FreeMarkerTemplateAvailabilityProvider.FreeMarkerTemplateAvailabilityRuntimeHints;
|
||||
import org.springframework.boot.testsupport.classpath.resources.WithResource;
|
||||
import org.springframework.core.io.DefaultResourceLoader;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Tests for {@link FreeMarkerTemplateAvailabilityProvider}.
|
||||
*
|
||||
* @author Andy Wilkinson
|
||||
*/
|
||||
class FreeMarkerTemplateAvailabilityProviderTests {
|
||||
|
||||
private final TemplateAvailabilityProvider provider = new FreeMarkerTemplateAvailabilityProvider();
|
||||
|
||||
private final ResourceLoader resourceLoader = new DefaultResourceLoader();
|
||||
|
||||
private final MockEnvironment environment = new MockEnvironment();
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/home.ftlh")
|
||||
void availabilityOfTemplateInDefaultLocation() {
|
||||
assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(),
|
||||
this.resourceLoader))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void availabilityOfTemplateThatDoesNotExist() {
|
||||
assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(),
|
||||
this.resourceLoader))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "custom-templates/custom.ftlh")
|
||||
void availabilityOfTemplateWithCustomLoaderPath() {
|
||||
this.environment.setProperty("spring.freemarker.template-loader-path", "classpath:/custom-templates/");
|
||||
assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(),
|
||||
this.resourceLoader))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "custom-templates/custom.ftlh")
|
||||
void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() {
|
||||
this.environment.setProperty("spring.freemarker.template-loader-path[0]", "classpath:/custom-templates/");
|
||||
assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(),
|
||||
this.resourceLoader))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/prefix/prefixed.ftlh")
|
||||
void availabilityOfTemplateWithCustomPrefix() {
|
||||
this.environment.setProperty("spring.freemarker.prefix", "prefix/");
|
||||
assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(),
|
||||
this.resourceLoader))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithResource(name = "templates/suffixed.freemarker")
|
||||
void availabilityOfTemplateWithCustomSuffix() {
|
||||
this.environment.setProperty("spring.freemarker.suffix", ".freemarker");
|
||||
assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(),
|
||||
this.resourceLoader))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRegisterFreeMarkerTemplateAvailabilityPropertiesRuntimeHints() {
|
||||
assertThat(AotServices.factories().load(RuntimeHintsRegistrar.class))
|
||||
.hasAtLeastOneElementOfType(FreeMarkerTemplateAvailabilityRuntimeHints.class);
|
||||
RuntimeHints hints = new RuntimeHints();
|
||||
new FreeMarkerTemplateAvailabilityRuntimeHints().registerHints(hints, getClass().getClassLoader());
|
||||
TypeHint typeHint = hints.reflection().getTypeHint(FreeMarkerTemplateAvailabilityProperties.class);
|
||||
assertThat(typeHint).isNotNull();
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user