Spring Boot fundamentals

  1. What is Spring Boot? Why we use it over plain Spring ?
  2. What is auto-configuration ?
  3. What does @SpringBootApplication do ?
  4. What are Spring Boot starters ?
  5. How to create Spring Boot project ?
  6. What is the embedded server ? Default ?
  7. Explain the main class and SpringApplication.run()
  8. application.properties vs application.yml ?
  9. What is @RestController vs @Controller?
  10. What are Common REST annotations ?
  11. @RequestParam vs @PathVariable ?
  12. Whats the use of @RequestBody ?
  13. What is ResponseEntity ?
  14. List out some Spring Boot DevTools ?
  15. What are the basic best pracices in the Spring Boot Application ? 
  16. 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)

 
What does @SpringBootApplication do ?

=> @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

 
What are Spring Boot starters ?

=> 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

  1. Open the Spring Initializr https://start.spring.io

  2. Provide the Group and Artifact name

  3. Now Click on the button Generate

  4. When we click on the button Generate, it starts packaging the project in a .rar file and downloads the project

  5. Extract the RAR file

  6. Import the folder in STS or Eclipse IDE

    File → Import → Existing Maven Project

Creating Spring Boot project using STS (Spring Tool Suite)

  1. Open the STS

  2. File → New → Maven Projects

  3. Select the maven-archetype-quickstart and click Next

  4. Provide Group ID, Artifact ID and FINISH

  5. Now, Open App.java, we can see some default code

  6. Open POM file and add Java version inside the tag properties

    <java.version>1.8</java.version>

  7. 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
    }
}
 

What are Common REST annotations ? 
 
  1. @GetMapping
  2. @PostMapping
  3. @PutMapping
  4. @DeleteMapping
  5. @PatchMapping
 
@RequestParam vs @PathVariable ?

=> 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);

}


What is ResponseEntity ?

=> 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
    }
}

 
List out some Spring Boot DevTools ?

=> Spring Boot DevTools (spring-boot-devtools) is a module that significantly improves the development experience by providing features focused on faster feedback loops and developer productivity. It's automatically disabled in production.
 
most useful and commonly used features of DevTools 

FeatureDescriptionHow It Helps in Development
Automatic RestartTriggers application restart when classpath changes (code, properties, templates).No manual restart — save file → instant reload.
LiveReloadWorks with a browser extension to refresh the page automatically on restart.See UI changes instantly without manual refresh.
Remote Debug SupportEnables remote debugging when running from IDE.Debug production-like deployment locally.
Property Defaults RelaxationDisables caching for templates (Thymeleaf, FreeMarker), enables debug logging for web, etc.See changes in HTML/CSS/JS without clearing cache.
Global SettingsSettings in ~/.spring-boot-devtools.properties apply to all projects.Consistent dev experience across projects.
Fast Restart with DevToolsUses a separate classloader for your code — restarts only your code, not libraries.Much faster than full restart.
Disabled in ProductionAutomatically disabled when packaged as JAR/WAR (via spring.devtools.restart.enabled=false).

No performance impact in production.


How to Add DevTools (in pom.xml)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>  <!-- Important — only for dev -->
    <optional>true</optional>
</dependency>

Browser LiveReload Extension

=> Install LiveReload extension in Chrome/Firefox.
=> Enable it on your page → browser auto-refreshes on server restart.

=> This spring-boot-devtools module is a must-have for every Spring Boot developer — saves hours during development

What are the basic best pracices in the Spring Boot Application 

  1. Thin Controllers 
  2. Use DTOs 
  3. Validation 
  4. Logging  

1. Thin Controllers
 
=> Controllers should be lean — only handle HTTP concerns (receive request, extract parameters, call service, return response).
=> No business logic in controller — delegate to Service layer.

2. Use DTOs
 
=> Never expose entity classes directly in API responses/requests.
=> Use separate DTO classes (plain POJOs or records) for input/output.
=> Example: Use EmployeeRequestDto, EmployeeResponseDto instead of exposing EmployeeEntity (JPA)
=> Benefit: Hide internal details, version APIs safely, avoid lazy loading issues, better validation control.

3. Validation

=> Use Bean Validation annotations (@NotNull, @Size, @Email, @Positive, etc.) on DTO fields
=> Add @Valid on controller parameters
@PostMapping
public ResponseEntity<?> create(@Valid @RequestBody EmployeeRequestDto dto) { ... }
=> Handle validation errors with @ControllerAdvice and BindingResult
=> Benefit: Automatic validation, consistent error responses, no manual checks.
 
4. Logging

=> Use SLF4J with Logback (default in Spring Boot).
=> Log at appropriate levels
        info() — important events (startup, request received).
        debug() — detailed flow (method entry/exit, parameters).
        error() — exceptions with stack trace.
=> Never use System.out.println() — use logger.
=> Add request IDs for tracing in logs. 
=> Benefit: Debuggable production issues, monitoring, structured logs. 

Explain few Spring Boot annotations that you know

_____________________________________________________________________

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): 

  1. @GetMapping("/hello") returning "Hello Spring Boot".
  2. @GetMapping("/greet/{name}") with @PathVariable.
  3. @GetMapping("/search") with @RequestParam name.
  4. @GetMapping with multiple @RequestParam (name, age).
  5. @RequestParam with defaultValue.
  6. @RequestParam(required = false).
  7. @PostMapping("/echo") with @RequestBody String → return same.
  8. @PostMapping("/person") with simple Person DTO → return it.
  9. Return ResponseEntity.ok() and ResponseEntity.status(201).
  10. Return ResponseEntity.notFound().build().
  11. Custom header with ResponseEntity.
  12. application.properties: server.port=8081.
  13. application.yml equivalent.
  14. @Value("${server.port}") injection.
  15. Custom property (app.name=MyApp) + @Value.
  16. 16–20. Mix: Employee DTO POST/GET, validation with @NotBlank, error response.
Note : Commit to GitHub at end