Bootstrapping Using spring-webmvc
Maven Dependencies
First, we need the spring-webmvc dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.0.RELEASE</version>
</dependency
The Java-based Web Configuration
Next, we’ll add the configuration class that has the @Configuration annotation:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = “com.baeldung.controller”)
public class WebConfig {}
Here, unlike the Spring Boot solution, we’ll have to explicitly define @EnableWebMvc for setting up default Spring MVC Configurations and @ComponentScan to specify packages to scan for components.
The @EnableWebMvc annotation provides the Spring Web MVC configuration such as setting up the dispatcher servlet, enabling the @ Controller and the @RequestMapping annotations and setting up other defaults.
@ComponentScan configures the component scanning directive, specifying the packages to scan.
Next, we need to add a class that implements the WebApplicationInitializer interface:
public class AppInitializer implements WebApplicationInitializer {
@Override public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.scan(“com.baeldung”); container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container.addServlet(“mvc”, new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping(“/”); }
}
Here, we’re creating a Spring context using the AnnotationConfigWebApplicationContext class, which means we’re using only annotation-based configuration. Then, we’re specifying the packages to scan for components and configuration classes.
Finally, we’re defining the entry point for the web application – the DispatcherServlet.
This class can entirely replace the web.xml file from <3.0 Servlet versions.
XML Configuration
Let’s also have a quick look at the equivalent XML web configuration:
<context:component-scan base-package=”com.baeldung.controller” />
<mvc:annotation-driven />
We can replace this XML file with the WebConfig class above.
To start the application, we can use an Initializer class that loads the XML configuration or a web.xml file.