Spring Boot
1: Bootstrap a Web Application with Spring 5
The chapter 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.
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
-
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.
Let’s also have a look at a solution using the core spring-webmvc library.