上QQ阅读APP看书,第一时间看更新
Enabling Web MVC using @EnableWebMvc
To be able to make use of the Spring MVC features, we need to have one class that has been annotated with @Configuration, to be annotated with @EnableWebMvc. The @EnableWebMvc annotation, imports the Spring MVC configuration from the WebMvcConfigurationSupport class present in the Spring MVC framework. If we need to override any of the default imported configuration, we would have to implement the WebMvcConfigurer interface present in the Spring MVC framework and override the required methods.
We will create an AppConfiguration class with the following definition:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.nilangpatel.worldgdp")
public class AppConfiguration implements WebMvcConfigurer{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
}
In the previous configuration, a few important things to note are as follows:
- @EnableWebMvc: This imports the Spring MVC related configuration.
- @ComponentScan: This is used for declaring the packages that have to be scanned for Spring components (which can be @Configuration, @Service, @Controller, @Component, and so on). If no package is defined, then it scans starting from the package where the class is defined.
- WebMvcConfigurer: We are going to implement this interface to override some of the default Spring MVC configuration seen in the previous code.