Spring Boot fundamentals
- What is Spring Boot? Why we use it over plain Spring ?
- What is auto-configuration ?
- What does @SpringBootApplication do ?
- What are Spring Boot starters ?
- How to create Spring Boot project ?
- What is the embedded server ? Default ?
- Explain the main class and SpringApplication.run()
- application.properties vs application.yml ?
- What is @RestController vs @Controller?
- What are Common REST annotations ?
- @RequestParam vs @PathVariable ?
- Whats the use of @RequestBody ?
- What is ResponseEntity ?
- List out some Spring Boot DevTools ?
- What are the basic best pracices in the Spring Boot Application ?
- Explain few Spring Boot annotations that you know
What is Spring Boot? Why we use it over plain Spring ?
=> Spring Boot is an opinionated, convention-over-configuration framework on top of Spring.
=> It simplifies the setup with auto-configuration, embedded servers and starter dependencies.
=> Benefits : Faster development, production-ready defaults, no xml/web.xml, easy testing
What is auto-configuration ?
=> Spring Boot scans classpath and auto-configures beans (Eg. sees H2 on classpath and configures DataSource)
=> Enabled by @EnableAutoConfiguration (This is the part of @SpringBootApplication)
=> @SpringBootApplication = @EnableAutoConfiguration + @ComponentScan + @Configuration
=> @EnableAutoConfiguration : Enables Spring Boot Auto Configuration mechanism
=> @ComponentScan : Scans the package where the application is located
=> @Configuration : Allows us to register extra beans in the context or import additional configuration classes
=> Spring Boot Starters feature simplifies the project setup
=> A Starter is a simple dependency that brings in everything we need for a particular technology or a feature
=> Example in pom.xml file :
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
=> With the above two dependencies, we can get full web MVC + JPA stack, all versions compatible, auto-configuration enabled
=> Before Spring Boot, setting up a Spring Project was painful, because,
We had to add the dozens of dependencies (Spring Core, Spring MVC, Jackson, Tomcat, etc) manually
Version compatibility issues (Wrong versions caused runtime errors)
Boiler plate lines in pom.xml or build.gradle even for a just simple web app
=> Spring Boot starters solved the above problems
Summary :
=> Just add the starter in pom.xml file -> Spring Boot autoconfigures
=> Spring Boot parent pom manages version compatibility issues
=> One dependency instead of 10-25 dependencies. ie. reduces boiler plate code
=> Allows us to focus on business logic, not setup
How to create Spring Boot project ?
We can create Spring Boot Projects using by either Spring Initializr or STS (Spring Tool Suite)
Creating Spring Boot project using Spring Initializr
Open the Spring Initializr https://start.spring.io
Provide the Group and Artifact name
Now Click on the button Generate
When we click on the button Generate, it starts packaging the project in a .rar file and downloads the project
Extract the RAR file
Import the folder in STS or Eclipse IDE
File → Import → Existing Maven Project
Creating Spring Boot project using STS (Spring Tool Suite)
Open the STS
File → New → Maven Projects
Select the maven-archetype-quickstart and click Next
Provide Group ID, Artifact ID and FINISH
Now, Open App.java, we can see some default code
Open POM file and add Java version inside the tag properties
<java.version>1.8</java.version>
In order to make it a Spring Boot Project, we need to add spring-boot-starter-parent and spring-boot-starter-web dependencies in pom.xml
What is the embedded server ? Default ?
=> Tomcat (in web starter). Alternatives: Jetty, Undertow
Explain the main class and SpringApplication.run()
=> Entry point with @SpringBootApplication and public static void main(String[] args) { SpringApplication.run(MyApp.class, args); }
application.properties vs application.yml
=> Both for configuration
=> yml is hierarchical, more readable for complex settings
What is @RestController vs @Controller?
=> Both are used to define classes that handle HTTP requests, but behave differently in return data
@Controller
=> By default, the return value is interpreted as view name (a template to render)
=> If we want to return raw data (JSON/XML) instead of a view, we must need to add @ResponseBody on the method or class.
=> Example :
@Controller
public class WebController {
@GetMapping("/home")
public String home() {
return "home"; // Returns view name "home.html" or "home.jsp"
}
@GetMapping("/api/data")
@ResponseBody // Required to return JSON
public String getData() {
return "{\"message\":\"Hello\"}";
}
}
@RestController
=> @RestController = @Controller + @ResponseBody
=> Automatically adds @ResponseBody to all methods in the class.
=> Return data is JSON/XML by default
=> Almost all the modern Spring Boot applications uses @RestController than @Controller
=> Example :
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello World"; // Automatically converted to JSON/text response
}
@GetMapping("/user")
public User getUser() {
return new User("Virat", 36); // Automatically serialized to JSON
}
}
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
=> Both @PathVariable and @RequestParam use the values from the URL
=> @PathVariable for URL path
=> @RequestParam for query params
=> Example URL :
URL we hit for path variable localhost:8080/insured/Ajith/20
URL we hit for RequestParam : localhost:8080/insured?name=Ajith&age=20
@PathVariable
=> Uses the url where we have path variables like this : localhost:8080/insured/Ajith/20
Example :
Method :
@RestController
public class MyController{
@RequestMapping(path=”/insured/{name}/{age}”)
public String getMessage(@PathVariable (“name”) String name,
@PathVariable(“age”) String age){
return String.format(“%s is %s years old”, name, age);
}
}
URL that we hit in the browser : localhost:8080/Ajith/20
Output : Ajith is 20 years old
@RequestParam
=> Uses the url where we have query parameters like this : localhost:8080/insured?name=Ajith&age=20
Example :
Method :
@RequestMapping(path=”/insured/”)
public String getMessage(@RequestParam(“name” String insuredName,
@RequestParam String age){
return String.format(“%s is %s years old”, insuredName, age);
}
=> ResponseEntity is a class in Spring Framework that represents the entire HTTP response including status code, headers, and body.
Why Use ResponseEntity?
In a @RestController, methods normally return the body only (e.g., a POJO or String), and Spring automatically sets:
Status code = 200 OK
Content-Type = application/json
But many times you need to customize the response:
Return 201 Created for POST.
Return 404 Not Found.
Add custom headers (e.g., Location header for created resource).
Return different status for error cases.
ResponseEntity lets you set all these explicitly.
ResponseEntity<T> response = new ResponseEntity<>(body, headers, statusCode);
// or using builders
ResponseEntity.ok(body) // 200 OK
ResponseEntity.created(locationUri).body(body) // 201 Created
ResponseEntity.notFound().build() // 404 No Content
=> Benefit : No need to use @ResponseStatus everywhere.
=> Practical Example :
@RestController
@RequestMapping("/employees")
public class EmployeeController {
// 200 OK — simple success
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
Employee emp = employeeService.findById(id);
if (emp != null) {
return ResponseEntity.ok(emp); // 200 + body
}
return ResponseEntity.notFound().build(); // 404
}
// 201 Created — with Location header
@PostMapping
public ResponseEntity<Employee> createEmployee(@RequestBody Employee emp) {
Employee saved = employeeService.save(emp);
URI location = URI.create("/employees/" + saved.getId());
return ResponseEntity.created(location).body(saved);
}
// Custom headers + status
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEmployee(@PathVariable Long id) {
employeeService.delete(id);
return ResponseEntity.noContent()
.header("X-Deleted-Id", String.valueOf(id))
.build(); // 204 + custom header
}
}
| Feature | Description | How It Helps in Development |
|---|---|---|
| Automatic Restart | Triggers application restart when classpath changes (code, properties, templates). | No manual restart — save file → instant reload. |
| LiveReload | Works with a browser extension to refresh the page automatically on restart. | See UI changes instantly without manual refresh. |
| Remote Debug Support | Enables remote debugging when running from IDE. | Debug production-like deployment locally. |
| Property Defaults Relaxation | Disables caching for templates (Thymeleaf, FreeMarker), enables debug logging for web, etc. | See changes in HTML/CSS/JS without clearing cache. |
| Global Settings | Settings in ~/.spring-boot-devtools.properties apply to all projects. | Consistent dev experience across projects. |
| Fast Restart with DevTools | Uses a separate classloader for your code — restarts only your code, not libraries. | Much faster than full restart. |
| Disabled in Production | Automatically disabled when packaged as JAR/WAR (via spring.devtools.restart.enabled=false). | No performance impact in production. |
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope> <!-- Important — only for dev -->
<optional>true</optional>
</dependency>
=> Install LiveReload extension in Chrome/Firefox.
- Thin Controllers
- Use DTOs
- Validation
- Logging
public ResponseEntity<?> create(@Valid @RequestBody EmployeeRequestDto dto) { ... }
_____________________________________________________________________
Coding Practice :
=> Create new Spring Boot project at https://start.spring.io
Group: com.example
Artifact: demo
Dependencies: Spring Web
=> Import in IntelliJ → run → verify http://localhost:8080
Exercises (create @RestController class):
- @GetMapping("/hello") returning "Hello Spring Boot".
- @GetMapping("/greet/{name}") with @PathVariable.
- @GetMapping("/search") with @RequestParam name.
- @GetMapping with multiple @RequestParam (name, age).
- @RequestParam with defaultValue.
- @RequestParam(required = false).
- @PostMapping("/echo") with @RequestBody String → return same.
- @PostMapping("/person") with simple Person DTO → return it.
- Return ResponseEntity.ok() and ResponseEntity.status(201).
- Return ResponseEntity.notFound().build().
- Custom header with ResponseEntity.
- application.properties: server.port=8081.
- application.yml equivalent.
- @Value("${server.port}") injection.
- Custom property (app.name=MyApp) + @Value.
- 16–20. Mix: Employee DTO POST/GET, validation with @NotBlank, error response.