11.3 Writing the code
To finish our application we need to create a single Java file. Maven will compile sources from src/main/java
by default so you need to create that folder structure, then add a file named src/main/java/Example.java
:
import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.stereotype.*; import org.springframework.web.bind.annotation.*; _@RestController_ _@EnableAutoConfiguration_ public class Example { _@RequestMapping("/")_ String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(Example.class, args); } }
Although there isn’t much code here, quite a lot is going on. Let’s step through the important parts.
11.3.1 The @RestController and @RequestMapping annotations
The first annotation on our Example
class is @RestController
. This is known as a stereotype annotation. It provides hints for people reading the code, and for Spring, that the class plays a specific role. In this case, our class is a web @Controller
so Spring will consider it when handling incoming web requests.
The @RequestMapping
annotation provides “routing” information. It is telling Spring that any HTTP request with the path “/” should be mapped to the home
method. The @RestController
annotation tells Spring to render the resulting string directly back to the caller.
Tip | |
---|---|
The @RestController and @RequestMapping annotations are Spring MVC annotations (they are not specific to Spring Boot). See the MVC section in the Spring Reference Documentation for more details. |
11.3.2 The @EnableAutoConfiguration annotation
The second class-level annotation is @EnableAutoConfiguration
. This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web
added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.
Starters and Auto-Configuration
Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. You are free to pick-and-choose jar dependencies outside of the starters and Spring Boot will still do its best to auto-configure your application.
11.3.3 The “main” method
The final part of our application is the main
method. This is just a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication
class by calling run
. SpringApplication
will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server. We need to pass Example.class
as an argument to the run
method to tell SpringApplication
which is the primary Spring component. The args
array is also passed through to expose any command-line arguments.