Spring Top

Finally announcing a new course. The Early Bird Price of the upcoming “Learn Spring” course will permanently increase by $50 on Friday:

>> GET ACCESS

REST Top

Finally announcing a new course. The Early Bird Price of the upcoming “Learn Spring” course will permanently increase by $50 on Friday:

>> GET ACCESS

1. Overview

The tutorial illustrates how to Bootstrap a Web Application with Spring.

We’ll look into the Spring Boot solution for bootstrapping the application and also see a non-Spring Boot approach.

We’ll primarily use Java configuration, but also have a look at their equivalent XML configuration.

Further reading:

Spring Boot Tutorial – Bootstrap a Simple Application

This is how you start understanding Spring Boot.

Read more

Configure a Spring Boot Web Application

Some of the more useful configs for a Spring Boot application.

Read more

Migrating from Spring to Spring Boot

See how to properly migrate from a Spring to Spring Boot.

Read more

2. Bootstrapping Using Spring Boot

2.1. Maven Dependency

First, we’ll need the spring-boot-starter-web dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>

This starter includes:

  • spring-web and the spring-webmvc module that we need for our Spring web application
  • a Tomcat starter so that we can run our web application directly without explicitly installing any server

2.2. Creating a Spring Boot Application

The most straight-forward way to get started using Spring Boot is to create a main class and annotate it with @SpringBootApplication:

@SpringBootApplication
public class SpringBootRestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestApplication.class, args);
    }
}

This single annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan.

By default, it will scan all the components in the same package or below.

Next, for Java-based configuration of Spring beans, we need to create a config class and annotate it with @Configuration annotation:

@Configuration
public class WebConfig {

}

This annotation is the main artifact used by the Java-based Spring configuration; it is itself meta-annotated with @Component, which makes the annotated classes standard beans and as such, also candidates for component-scanning.

The main purpose of @Configuration classes is to be sources of bean definitions for the Spring IoC Container. For a more detailed description, see the official docs.

Let’s also have a look at a solution using the core spring-webmvc library.

3. Bootstrapping Using spring-webmvc

3.1. 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>

3.2. 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.

3.3. The Initializer Class

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.

4. 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. For more details on these two approaches, check out our previous article.

5. Conclusion

In this article, we looked into two popular solutions for bootstrapping a Spring web application, one using the Spring Boot web starter and other using the core spring-webmvc library.

In the next article on REST with Spring, I cover setting up MVC in the project, configuration of the HTTP status codes, payload marshalling, and content negotiation.

As always, the code presented in this article is available over on Github. This is a Maven based project, so it should be easy to import and run as it is.

Spring bottom

Finally announcing a new course. The Early Bird Price of the upcoming “Learn Spring” course will permanently increase by $50 on Friday:

>> GET ACCESS

REST bottom

Finally announcing a new course. The Early Bird Price of the upcoming “Learn Spring” course will permanently increase by $50 on Friday:

>> GET ACCESS

newest oldest most voted
Notify of
Chris Beams
Guest
Chris Beams

Hi Eugen,

Note that as of Spring 3.1 RC2, use of [email protected](Configuration.class) is no longer necessary. See https://jira.springsource.org/browse/SPR-8808.

Would you mind updating your examples to depend on RC2 and eliminating this bit from the @ComponentScan definition?

Thanks for a great series of posts!

Eugen Paraschiv
Guest

Thank you for letting me know (as well as for the actual work). The update is now included in the article.

Amol Khanolkar
Guest
Amol Khanolkar

Can you tell me some advantages of using java based configurations over XML based and when to choose which one?

Torben Vesterager
Guest
Torben Vesterager

Simple – you have one file for configuration and functionality – instead of jumping between 2

Eugen Paraschiv
Guest

Type safety is a big one, and ease of use is a close second.

Stephane
Guest
Stephane

And you can use a debugger if needed.

Eugen Paraschiv
Guest

I updated the article – thanks.

Stephane
Guest
Stephane

It’d be nice to also include a showcase on how to replace the web.xml file by a class implementing the WebApplicationInitializer interface.

Eugen Paraschiv
Guest

I am planning to discuss that in an upcoming article.

Stephane
Guest
Stephane

I could in fact do it, and it wasn’t that hard. The only thing that I could not cut is how to move the elements of the log4j config into a Java config. Google was dry on this one. Maybe your next article would shed some light on this 🙂 Thanks again.

Stephane
Guest
Stephane

It’s funny, my comment was automatically closed by a tag.

Anuj Patel
Guest
Anuj Patel

Thanks ! It really helps to clear concepts and will help while doing actual Implementation