WebMvcConfigurer is a powerful interface in Spring MVC (and by extension, Spring Boot) that allows you to customize the default configuration of the web application. It provides a set of callback methods that you can override in your configuration class to fine-tune various aspects of how Spring MVC handles requests, renders views, serves static resources, and more.
Spring Boot provides a lot of auto-configuration for Spring MVC, which is great for getting started quickly. However, there are many scenarios where you need to deviate from the defaults or add custom logic. WebMvcConfigurer allows you to:
Extend or modify Spring Boot's auto-configuration: You don't have to completely disable auto-configuration; you can simply add or modify specific parts of the MVC setup.
Apply global settings: It's ideal for configurations that apply across your entire web application.
Maintain separation of concerns: By implementing this interface in a dedicated configuration class (often annotated with @Configuration), you keep your MVC-related configurations separate from your main application logic.
How to use WebMvcConfigurer
You typically create a configuration class that implements WebMvcConfigurer and annotate it with @Configuration. Then, you override the specific methods you want to customize.
Java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Add custom interceptors
// registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/api/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// Configure static resource handling
// registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// Map URLs directly to views without a controller method
// registry.addViewController("/home").setViewName("home");
// registry.addViewController("/login").setViewName("login");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// Configure Cross-Origin Resource Sharing (CORS)
// registry.addMapping("/api/**")
// .allowedOrigins("http://localhost:3000")
// .allowedMethods("GET", "POST", "PUT", "DELETE")
// .allowCredentials(true);
}
// ... many other methods to override
}
Common use cases and methods
Here are some of the most commonly overridden methods of WebMvcConfigurer:
addInterceptors(InterceptorRegistry registry):
Purpose: To register Spring MVC interceptors. Interceptors allow you to pre-process requests before they reach the controller and post-process responses after the controller has handled them.
Use cases: Logging, authentication/authorization checks, performance monitoring, request/response manipulation.
addResourceHandlers(ResourceHandlerRegistry registry):
Purpose: To configure how static resources (like CSS, JavaScript, images, and other files) are served.
Use cases: Specifying custom locations for static files (e.g., classpath:/my-static-files/), setting cache control headers, or serving resources from external paths.
addViewControllers(ViewControllerRegistry registry):
Purpose: To register simple automated controllers that directly map a URL path to a view name, without needing a dedicated @Controller class or method.
Use cases: Mapping a home page (/), a login page (/login), or other simple informational pages where no complex logic is required.
addCorsMappings(CorsRegistry registry):
Purpose: To configure Cross-Origin Resource Sharing (CORS). CORS is a security mechanism that allows web browsers to make requests to a different domain than the one that served the original web page.
Use cases: Enabling your frontend application (e.g., a React or Angular app running on localhost:3000) to communicate with your Spring Boot backend API.
configureMessageConverters(List<HttpMessageConverter<?>> converters):
Purpose: To customize the HttpMessageConverters that Spring MVC uses to convert HTTP request bodies to Java objects and Java objects to HTTP response bodies (e.g., JSON to Java object, Java object to JSON).
Use cases: Adding custom message converters for specific media types, or configuring existing converters (e.g., customizing Jackson's JSON serialization/deserialization).
configureContentNegotiation(ContentNegotiationConfigurer configurer):
Purpose: To configure how Spring MVC determines the content type of the response (e.g., JSON, XML, HTML) based on the request (e.g., Accept header, URL extension, or request parameter).
Use cases: Setting a default content type, enabling or disabling path extension-based content negotiation, or favoring a specific media type.
configurePathMatch(PathMatchConfigurer configurer):
Purpose: To configure options related to URL path matching, such as whether to use parsed PathPatterns or String pattern matching with PathMatcher, or whether to match trailing slashes.
Use cases: Ensuring consistent URL matching behavior across your application.
WebMvcConfigurer vs. @EnableWebMvc
WebMvcConfigurer (recommended for Spring Boot): When used in a Spring Boot application, implementing WebMvcConfigurer allows you to customize the auto-configured Spring MVC settings. You extend and modify the existing behavior without completely overriding it. This is generally the preferred approach in Spring Boot.
@EnableWebMvc: This annotation is typically used in traditional Spring MVC applications (without Spring Boot's auto-configuration) to enable Spring MVC. If you use @EnableWebMvc in a Spring Boot application, it will disable Spring Boot's default MVC auto-configuration, and you will be responsible for providing all necessary MVC beans and configurations yourself. This is rarely necessary unless you have very specific and complex requirements that require complete control over the MVC setup.