Spring Boot AutoConfigure provides auto-configuration capabilities that automatically configure Spring applications based on jar dependencies present on the classpath
—
Spring Boot AutoConfigure provides configuration properties for web applications including error handling, resource management, locale resolution, and web resource hints.
import org.springframework.boot.autoconfigure.web.*;
import org.springframework.boot.autoconfigure.web.format.*;Configuration properties for web error handling and error page customization.
@ConfigurationProperties(prefix = "server.error")
public class ErrorProperties {
/**
* Path of the error controller.
* Default is "/error".
*/
public String getPath();
public void setPath(String path);
/**
* Include the "exception" attribute in the error response.
* Default is false.
*/
public boolean isIncludeException();
public void setIncludeException(boolean includeException);
/**
* When to include the "stacktrace" attribute in the error response.
*/
public IncludeAttribute getIncludeStacktrace();
public void setIncludeStacktrace(IncludeAttribute includeStacktrace);
/**
* When to include the "message" attribute in the error response.
*/
public IncludeAttribute getIncludeMessage();
public void setIncludeMessage(IncludeAttribute includeMessage);
/**
* When to include the "errors" attribute (binding errors) in the error response.
*/
public IncludeAttribute getIncludeBindingErrors();
public void setIncludeBindingErrors(IncludeAttribute includeBindingErrors);
/**
* When to include the "path" attribute in the error response.
*/
public IncludeAttribute getIncludePath();
public void setIncludePath(IncludeAttribute includePath);
/**
* Get whitelabel error page configuration.
*/
public Whitelabel getWhitelabel();
public static class Whitelabel {
/**
* Whether to enable the default error page.
* Default is true.
*/
public boolean isEnabled();
public void setEnabled(boolean enabled);
}
/**
* Enum for controlling when attributes are included in error responses.
*/
public enum IncludeAttribute {
NEVER, // Never include the attribute
ALWAYS, // Always include the attribute
ON_PARAM // Include only when request parameter is present
}
}Configuration properties for general web concerns including resource handling and locale resolution.
@ConfigurationProperties("spring.web")
public class WebProperties {
/**
* Get the fixed locale.
* Null means use Accept-Language header.
*/
public Locale getLocale();
/**
* Set the fixed locale.
* Null means use Accept-Language header.
*/
public void setLocale(Locale locale);
/**
* Get the locale resolver strategy.
*/
public LocaleResolver getLocaleResolver();
public void setLocaleResolver(LocaleResolver localeResolver);
/**
* Get error handling configuration.
*/
public ErrorProperties getError();
/**
* Get resource handling configuration.
*/
public Resources getResources();
/**
* Resource handling configuration.
*/
public static class Resources {
/**
* Get static resource locations.
* Default includes classpath:/META-INF/resources/,
* classpath:/resources/, classpath:/static/, classpath:/public/
*/
public String[] getStaticLocations();
public void setStaticLocations(String[] staticLocations);
/**
* Whether to enable default resource handling.
* Default is true.
*/
public boolean isAddMappings();
public void setAddMappings(boolean addMappings);
/**
* Get resource chain configuration.
*/
public Chain getChain();
/**
* Get cache configuration.
*/
public Cache getCache();
/**
* Check if the resource locations have been customized.
*/
public boolean hasBeenCustomized();
public static class Chain {
/**
* Get whether resource chain is enabled.
*/
public Boolean getEnabled();
/**
* Whether to enable resource chain.
* Can be auto-enabled if certain dependencies are present.
*/
public void setEnabled(Boolean enabled);
/**
* Whether to enable caching for the resource chain.
* Default is true.
*/
public boolean isCache();
public void setCache(boolean cache);
/**
* Get resource chain strategy configuration.
*/
public Strategy getStrategy();
/**
* Whether to compress resources.
*/
public boolean isCompressed();
public void setCompressed(boolean compressed);
}
/**
* Resource chain strategy configuration.
*/
public static class Strategy {
/**
* Get fixed version strategy configuration.
*/
public Fixed getFixed();
/**
* Get content-based version strategy configuration.
*/
public Content getContent();
}
/**
* Content-based versioning strategy.
*/
public static class Content {
/**
* Whether to enable content-based versioning.
*/
public boolean isEnabled();
public void setEnabled(boolean enabled);
/**
* Patterns for resources to apply content-based versioning.
*/
public String[] getPaths();
public void setPaths(String[] paths);
}
/**
* Fixed version strategy.
*/
public static class Fixed {
/**
* Whether to enable fixed versioning.
*/
public boolean isEnabled();
public void setEnabled(boolean enabled);
/**
* Patterns for resources to apply fixed versioning.
*/
public String[] getPaths();
public void setPaths(String[] paths);
/**
* Version string to use for fixed versioning.
*/
public String getVersion();
public void setVersion(String version);
}
public static class Cache {
/**
* Cache period for resources.
*/
public Duration getPeriod();
public void setPeriod(Duration period);
/**
* Cache control HTTP header settings.
*/
public Cachecontrol getCachecontrol();
/**
* Whether to use last modified header for caching.
* Default is true.
*/
public boolean isUseLastModified();
public void setUseLastModified(boolean useLastModified);
}
/**
* Cache-Control HTTP header configuration.
*/
public static class Cachecontrol {
/**
* Maximum time a response can be cached (max-age directive).
*/
public Duration getMaxAge();
public void setMaxAge(Duration maxAge);
/**
* Indicate that the cached response can be reused only if there is no
* fresh response from the origin server (no-cache directive).
*/
public Boolean getNoCache();
public void setNoCache(Boolean noCache);
/**
* Indicate that the response must not be stored (no-store directive).
*/
public Boolean getNoStore();
public void setNoStore(Boolean noStore);
/**
* Indicate that once the response becomes stale, it must be revalidated (must-revalidate directive).
*/
public Boolean getMustRevalidate();
public void setMustRevalidate(Boolean mustRevalidate);
/**
* Indicate that transformations should not be applied (no-transform directive).
*/
public Boolean getNoTransform();
public void setNoTransform(Boolean noTransform);
/**
* Indicate that the response is cacheable by any cache (public directive).
*/
public Boolean getCachePublic();
public void setCachePublic(Boolean cachePublic);
/**
* Indicate that the response is intended for a single user (private directive).
*/
public Boolean getCachePrivate();
public void setCachePrivate(Boolean cachePrivate);
/**
* Indicate that once the response becomes stale, a shared cache must revalidate (proxy-revalidate directive).
*/
public Boolean getProxyRevalidate();
public void setProxyRevalidate(Boolean proxyRevalidate);
/**
* Maximum time a stale response can be used while revalidating (stale-while-revalidate directive).
*/
public Duration getStaleWhileRevalidate();
public void setStaleWhileRevalidate(Duration staleWhileRevalidate);
/**
* Maximum time a stale response can be used when errors occur (stale-if-error directive).
*/
public Duration getStaleIfError();
public void setStaleIfError(Duration staleIfError);
/**
* Maximum time a shared cache can store the response (s-maxage directive).
*/
public Duration getSMaxAge();
public void setSMaxAge(Duration sMaxAge);
/**
* Convert this configuration to Spring's CacheControl object.
*/
public org.springframework.http.CacheControl toHttpCacheControl();
}
}
/**
* Locale resolver strategies.
*/
public enum LocaleResolver {
FIXED, // Use fixed locale
ACCEPT_HEADER // Use Accept-Language header
}
}Conditional annotation that checks whether the Spring resource handling chain is enabled.
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnEnabledResourceChainCondition.class)
public @interface ConditionalOnEnabledResourceChain {
}RuntimeHintsRegistrar for default locations of web resources, used with GraalVM native images.
public class WebResourcesRuntimeHints implements RuntimeHintsRegistrar {
/**
* Register runtime hints for web resources.
*/
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader);
}Formatters for dates, times, and date-times with customizable patterns.
public class DateTimeFormatters {
/**
* Create formatters with default patterns.
*/
public DateTimeFormatters();
/**
* Create new formatters with custom date format pattern.
*
* @param pattern the date format pattern or null for ISO format
* @return new DateTimeFormatters instance
*/
public DateTimeFormatters dateFormat(String pattern);
/**
* Create new formatters with custom time format pattern.
*
* @param pattern the time format pattern or null for ISO format
* @return new DateTimeFormatters instance
*/
public DateTimeFormatters timeFormat(String pattern);
/**
* Create new formatters with custom date-time format pattern.
*
* @param pattern the date-time format pattern or null for ISO format
* @return new DateTimeFormatters instance
*/
public DateTimeFormatters dateTimeFormat(String pattern);
}FormattingConversionService dedicated to web applications for formatting and converting values to/from the web.
public class WebConversionService extends DefaultFormattingConversionService {
/**
* Create a new WebConversionService with custom date/time formatters.
*
* @param dateTimeFormatters the date/time formatters to use
*/
public WebConversionService(DateTimeFormatters dateTimeFormatters);
}server:
error:
path: /error
include-exception: false
include-stacktrace: never # or 'always', 'on_param'
include-message: always
include-binding-errors: always
include-path: on_param
whitelabel:
enabled: truespring:
web:
resources:
static-locations:
- classpath:/static/
- classpath:/public/
- file:/var/www/
add-mappings: true
cache:
period: 1h
cachecontrol:
max-age: 3600
must-revalidate: true
chain:
enabled: true
cache: truespring:
web:
locale: en_US
locale-resolver: fixed # or 'accept-header'import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
@Controller
public class CustomErrorController implements ErrorController {
private final ErrorProperties errorProperties;
public CustomErrorController(ErrorProperties errorProperties) {
this.errorProperties = errorProperties;
}
@RequestMapping("${server.error.path:/error}")
public String handleError(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute(
"jakarta.servlet.error.status_code"
);
if (statusCode == 404) {
return "error/404";
} else if (statusCode == 500) {
return "error/500";
}
return "error/generic";
}
}import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebResourceConfiguration implements WebMvcConfigurer {
private final WebProperties webProperties;
public WebResourceConfiguration(WebProperties webProperties) {
this.webProperties = webProperties;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (webProperties.getResources().isAddMappings()) {
registry.addResourceHandler("/custom/**")
.addResourceLocations("classpath:/custom-static/")
.setCachePeriod(3600);
}
}
}import org.springframework.boot.autoconfigure.web.format.DateTimeFormatters;
import org.springframework.boot.autoconfigure.web.format.WebConversionService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.support.FormattingConversionService;
@Configuration
public class FormattingConfiguration {
@Bean
public FormattingConversionService conversionService() {
DateTimeFormatters formatters = new DateTimeFormatters()
.dateFormat("yyyy-MM-dd")
.timeFormat("HH:mm:ss")
.dateTimeFormat("yyyy-MM-dd'T'HH:mm:ss");
return new WebConversionService(formatters);
}
}import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import java.util.Locale;
@Configuration
public class LocaleConfiguration {
private final WebProperties webProperties;
public LocaleConfiguration(WebProperties webProperties) {
this.webProperties = webProperties;
}
@Bean
public LocaleResolver localeResolver() {
if (webProperties.getLocaleResolver() ==
WebProperties.LocaleResolver.FIXED) {
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.US);
return resolver;
} else {
AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
resolver.setDefaultLocale(Locale.US);
return resolver;
}
}
}ON_PARAM for sensitive information in productionACCEPT_HEADER for international applications