Spring Boot setup REST API Hello World on Window in 5 minutes with common mistakes solved
This process is harder than it looks. So I write this guide to help my team and anyone get more peace with Spring Boot setup.
Dependencies & Terms
Only one thing you need is IntelliJ IDEA
- IntelliJ Idea Community Edition (CE) IDE
Download here https://www.jetbrains.com/idea/download
Note that we will use the Free one (Community Edition)
In Java world, things is hard, you need IDE.
Then you got
- Maven (build tool)
** this is buddled with IntelliJ
Some project use Gradle but now we will stick with the classic one - JDK (Java Development Kit)
We will download this in IntelliJ — See step below
If you are confused JDK and JRE, you need JDK to dev and JRE to just run the Java app.
Spring Initializr
Spring Boot has the starter recipe for you https://start.spring.io/
Follow below image and click generate then you will have the zip downloaded to be extracted.
*** Do not forget to add Spring Web Dependencies***
Add the classic Hello World GET
Now you use IntelliJ Idea to open the folder.
You will see 2 things:
- IntelliJ suggest you to install JDK
you click to allow it to do so. - It will load the dependencies for you.
You don’t need explicit thing like you familiar with other tool like Node.js ‘snpm install
Java folder is deep by nature and you will get used to it.
You go to DemoApplication
file then add the GET hello world like below.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
Hit the green run button to start the Java server
Now you visit localhost:8080/hello
to see the result
Common Mistakes
Troubleshooting: Cannot see DemoApplication and no green button to run
You forget to add Spring Web
as dependencies in Initializr
Troubleshooting: zip end header not found
Go to your home folder like C:\Users\name\
Then delete the .m2
folder. IntelliJ will refetch the dependencies for you.
Troubleshooting: java: cannot find symbol
You forgot the line of import
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
Troubleshooting: Whilelabel Error Page
You forgot the @RestController
at the beginning
...
@SpringBootApplication
@RestController // add here
public class DemoApplication {
...
Hope this help !