Spring Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
REST Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

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.

Configure a Spring Boot Web Application

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

Migrating from Spring to Spring Boot

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

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 straightforward 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

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
REST bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
18 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Antonel Ernest Pazargic
Antonel Ernest Pazargic
6 years ago

Thank you for the good intro in setting up a spring based web application.

IMHO groovy application context configuration will get traction in the near future, just as gradle does over the maven.

It would be great if you are considering to migrate the example project to groovy context config.

Thank you.

Eugen Paraschiv
6 years ago

It’s definitely an idea that I’m considering for some of my next articles. Thanks for the suggestion – I’ll also remember to follow up here once I do. Cheers,
Eugen.

Sam
Sam
6 years ago

Hi, i downloaded the source code, could you please show me how to run it. Thanks.

Eugen Paraschiv
6 years ago
Reply to  Sam

Hey Sam – it’s a Maven project, so you can import it into the IDE of your choice. It’s also an Eclipse project, so – in case you’re using Eclipse, you can simply import it as a normal project. And you can of course build it from command line with Maven if you need to. Hope that helps. Cheers,
Eugen.

Alexandru Matei
Alexandru Matei
6 years ago

Eugen, can you please explain the necessity for

commons-logging
commons-logging

in spring-webmvc dependency ?

Why is that necessary in Spring 4?

Eugen Paraschiv
6 years ago

The reason you need to exlucde commons-logging is that – unfortunately – it’s the default in Spring, so it’s pulled in as a dependency (yes, even in Spring 4.1); so – first step is to exclude it, and then you’ll need to use a bridge to map it to something else (jcl-over-slf4j). Cheers,
Eugen.

Alexandru Matei
Alexandru Matei
6 years ago

I notice indeed in my target folder compiled with Maven + Spring 4.1.0 appears
commons-logging-1.1.1.jar

You mean that this commons-logging-1.1.1.jar added as a dependency side effect by Maven is too old ?

Eugen Paraschiv
6 years ago

It’s old as well (2007) but that’s not the main issue – it has other disadvantages. slf4j backed by logback is just a much better solution.

Alexandru Matei
Alexandru Matei
6 years ago

All right, thank you Eugen.

Although is a bit off topic, please allow a short comment

I had a hard time (for me as beginner) to run a
Spring Web MVC + Spring security application.

I had to set manually:

xml-apis
xml-apis
1.4.01

/dependency>

When building using Maven, it is pulling in the xml-apis jar 1.0.b2 which apparently is not compatible ?!

So without this workaround, my Spring web application is not loaded at all in the application server (GlassFish 4.1 in my case)

There are other people on the web discussing this problem in various situations.

Eugen Paraschiv
6 years ago

I never did deploy it in GlassFish, but yes, I found the discussions threads. One suggestion is to open a JIRA with Hibernate to upgrade the dependency (it’s pulled in by hibernate-entitymanager). In the meantime, I updated the project – thanks for the suggestion. Cheers,
Eugen.

Dale Ogilvie
Dale Ogilvie
6 years ago

What about using the Spring IO platform for your bootstrap? http://platform.spring.io/platform/

This is convenient to manage dependency versions.

Eugen Paraschiv
6 years ago
Reply to  Dale Ogilvie

That’s a good way to go, but it’s still very new. Using something that new is unfortunately not a viable option for a lot of projects, which is why I think going the standard route is still very useful. Also – understanding the standard route well before doing anything else that will “help” is also a good idea. That being said – I like the platform – it does make things easier. Cheers,
Eugen.

Nitin Sharma
Nitin Sharma
4 years ago

How I can download the boot up code. I am not able to understand the code structure.

Eugen Paraschiv
4 years ago
Reply to  Nitin Sharma

Hey Nitin – you can download the code from the link at the very end, or by simply cloning the repo and using the project there.
Hope that helps. Cheers,
Eugen.

Comments are closed on this article!