Spring Boot Cheatsheet
Â
Category | Command | Syntax / Description |
---|---|---|
Project Setup | Create project (Spring Initializr) | https://start.spring.io/ |
Project Setup | Run app |
mvn spring-boot:run or ./mvnw spring-boot:run
|
Project Setup | Build app | mvn clean install |
Annotations | @SpringBootApplication | Marks the main class with @SpringBootApplication
|
Annotations | @RestController | Used to create REST controllers |
Annotations | @RequestMapping | Maps HTTP requests to methods |
Annotations | @GetMapping | @GetMapping("/path") |
Annotations | @PostMapping | @PostMapping("/path") |
REST API | GET endpoint | @GetMapping("/hello") public String hello() { return "Hi"; } |
REST API | POST endpoint | @PostMapping("/user") public User add(@RequestBody User u) { return repo.save(u); } |
REST API | Path variable | @GetMapping("/user/{id}") public User get(@PathVariable int id) { return repo.findById(id); } |
Database | JPA Entity | @Entity public class User { @Id int id; String name; } |
Database | Repository Interface | public interface UserRepo extends JpaRepository<User, Integer> {} |
Database | DB Connection |
spring.datasource.url=... spring.datasource.username=... spring.datasource.password=...
|
App Properties | Set server port | server.port=8081 |
App Properties | Datasource config | spring.datasource.* = DB credentials |
Testing | Unit Test | @Test void testSomething() {} |
Testing | MockMvc Test | @Autowired MockMvc mvc; mvc.perform(...).andExpect(...); |