Skip to content

Instantly share code, notes, and snippets.

@sandipchitale
Last active July 23, 2023 06:19
Show Gist options
  • Save sandipchitale/fc4315881f946ac4952a38b4b3c0da6e to your computer and use it in GitHub Desktop.
Save sandipchitale/fc4315881f946ac4952a38b4b3c0da6e to your computer and use it in GitHub Desktop.
@EnableWebMvc notes #EnableWebMvc

Springboot skips auto-configure the WebMvcAutoConfiguration, because it finds that there is org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration bean, and why did that bean instantiate because the user had @EnableWebMvc annotation on a @Configuration class. This is really screwed up.

WebMvcAutoConfiguration: Matched: - @ConditionalOnClass found required classes 'jakarta.servlet.Servlet', 'org.springframework.web.servlet.DispatcherServlet', 'org.springframework.web.servlet.config.annotation.WebMvcConfigurer' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) Did not match: - @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) found beans of type 'org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport' org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration (OnBeanCondition)

When Springboot does configure the WebMvcAutoConfiguration, it will check the following conditions:

WebMvcAutoConfiguration matched: - @ConditionalOnClass found required classes 'jakarta.servlet.Servlet', 'org.springframework.web.servlet.DispatcherServlet', 'org.springframework.web.servlet.config.annotation.WebMvcConfigurer' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) - @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) did not find any beans (OnBeanCondition)

@Configuration
@EnableWebMvc // Simply enables default MVC config from WebMvc and disables auto-configuration by WebMvcAutoConfiguration
public static class OptIntoWebMvcMarkerConfiguration {
}
@Component
@EnableWebMvc // Simply enables default MVC config from WebMvc and disables auto-configuration by WebMvcAutoConfiguration
public static class ReplacingWebMvcConfigurer implements WebMvcConfigurer {
}
@Component
// lack pf @EnableWebMvc allows WebMvcAutoConfiguration to do it's default thing and you can add to it
// by implementing WebMvcConfigurer
public static class AdditionalWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
WebMvcConfigurer.super.addResourceHandlers(registry);
registry
.addResourceHandler("/customization/**")
.addResourceLocations("classpath:/customization/", "classpath:/static/");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment