Configuring Spring MVC to serve static files means registering resource handlers that map incoming URL patterns for assets like CSS, JavaScript, and images to the physical or classpath locations where those files actually live.
Key Points: • Implement WebMvcConfigurer and override addResourceHandlers to declare the mapping. • addResourceHandler defines the URL pattern clients will request, and addResourceLocations defines where Spring looks for matching files. • Multiple locations can be registered for a single pattern, and Spring checks them in order until a match is found. • setCacheControl or setCachePeriod on the registration lets you add browser caching headers for static assets. • Spring Boot auto-configures classpath:/static/, /public/, /resources/, and /META-INF/resources/ by default, so explicit configuration is mainly needed to customize behavior.
Example: Registering "/assets/**" mapped to "classpath:/static/assets/" means a browser request for /assets/logo.png is served straight from src/main/resources/static/assets/logo.png without touching a controller.
Code Example:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**")
.addResourceLocations("classpath:/static/assets/")
.setCachePeriod(3600);
}
}Interview Tip: A concise interview answer is:
"I implement WebMvcConfigurer and override addResourceHandlers, pairing a URL pattern like /assets/** with a physical or classpath location such as classpath:/static/assets/. That tells Spring MVC to serve matching requests as static files directly, and I can also set cache headers on that same registration."