Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

Spring Boot Tutorial for Beginners: Jumpstart Your Java Development

Published On: May 10, 2025

Spring Boot is a good fit for developing microservices, which are becoming increasingly common as scalable and self-contained application components. There is an increasing need for Spring Boot developers as more businesses use microservices. Learn them comprehensively in this Spring Boot Tutorial for Beginners. Before gaining expertise with hands-on exposure, go through our Spring Boot course syllabus.

Introduction to Spring Framework

An open-source, Java-based framework called Spring Boot makes it easier to create standalone, high-quality Spring apps. It adopts a subjective stance toward third-party libraries and the Spring platform, enabling you to get started with little setup.

Key Features and Advantages of Spring Framework

Here are the key features of Spring framework:

  • Auto-Configuration: Using the dependencies you’ve supplied, Spring Boot automatically sets up your application.
  • Standalone Apps: As Spring Boot may embed servers like Tomcat, Jetty, or Undertow right into the application, you can use the java -jar command to develop apps that can run on their own.
  • Opinionated Defaults: Spring Boot lets developers get started quickly without having to make a lot of judgments by offering sensible default configurations for a lot of options.
  • Starter Dependencies: Spring Boot provides sets of useful dependency descriptors called “Starter POMs” (for Maven) or “Starter Plugins” (for Gradle).
  • Production-Ready Features: Health checks, metrics, and externalized configuration are just some tools that Spring Boot offers to help manage applications in production.
  • No XML Configuration: Spring Boot minimizes the need for verbose XML configuration by prioritizing convention over common configuration.

The goal of Spring Boot is to make using Spring for Java development quicker, simpler, and more pleasurable. It enables developers to concentrate less on the underlying infrastructure configuration and more on the application’s business logic.

Difference Between Spring Boot and Traditional Spring

Although the Spring Framework is the foundation upon which Spring Boot is built, they have separate functions and provide unique experiences. Here is a comprehension:

FeatureTraditional SpringSpring Boot
Setup & ConfigurationRequires significant manual configuration (XML, annotations). More verbose.Minimal configuration needed due to auto-configuration. Convention over configuration.
DependenciesYou manage all dependencies explicitly.Provides “Starter POMs/Plugins” that bundle related dependencies. Simplifies dependency management.
DeploymentTypically deployed as WAR files to external application servers.Can create standalone executable JARs with embedded servers (Tomcat, Jetty, Undertow). Easier deployment.
Boilerplate CodeMore boilerplate code required.Reduces boilerplate code significantly.
OpinionatedUn-opinionated; offers high flexibility.Opinionated defaults for faster setup.
Production-ReadyRequires manual setup for production features.Includes production-ready features like health checks, metrics out-of-the-box.
Ease of UseSteeper learning curve due to manual configuration.Easier to get started with and faster development.
  • Traditional Spring: For creating enterprise Java applications, traditional Spring offers a thorough and incredibly adaptable framework. Although it needs more setup and configuration work, it allows you fine-grained control over every component of your application.
  • Spring Boot: Building Spring-based apps is made easier with the help of the opinionated toolkit known as Spring Boot. It uses starting dependencies and auto-configuration to get you up and running fast with little setup. 

Learn more with our Spring Boot Online Course Program.

Spring Boot Environmental Setup

Here is the environmental setup for Spring Boot:

  • Java Development Kit (JDK): Make sure your Java Development Kit (JDK) is compliant; it is usually advised to use version 8 or later. It is available for download from OpenJDK or Oracle distributions.
  • Build Tool: Select one of the following:
    • Maven: Install Apache Maven after downloading it.
    • Gradle: Install Gradle after downloading it.
  • Integrated Development Environment (IDE) (Optional but Recommended): Well-liked options that offer first-rate support for Spring Boot programming include IntelliJ IDEA, Eclipse, or Spring Tools Suite (STS).

After installing these, you may use the build tool or IDE features of your choice to begin generating Spring Boot projects.

Creating your First Spring Boot Application 

Let’s quickly build your first Spring Boot application. We’ll make use of Maven.

  • Go to Spring Initializr: Open your web browser and navigate to https://start.spring.io/.
  • Configure Your Project:
    • Select Maven as the tool for building.
    • Choose Java as the language.
    • Select the version of Spring Boot (typically the default stable version works well).
    • Enter the Artefact (such as demo) and Group (such as com.example).
    • Add a dependency: Look up and choose Spring Web. You can create web applications as a result.
  • Create the Project: The “GENERATE” button should be clicked. A ZIP file with the fundamental project structure will be downloaded as a result.
  • Extract and Open: The downloaded file should be unzipped. Using your IDE (IntelliJ, Eclipse, etc.), open the generated folder.
  • Create a Simple Controller: Build a new Java class called HelloController inside the src/main/java/com/example/demo (or your group/artifact name) directory. Include the following code:

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class HelloController {

    @GetMapping(“/hello”)

    public String hello() {

        return “Hello, Spring Boot!”;

    }

}

  • Run the application: Typically, the file DemoApplication.java (or a similar file) in the same base package serves as your primary application entry point. Use your IDE to launch this class as a Java application.
  • Access in Browser: After the application launches, launch your browser and navigate to http://localhost:8080/hello. The message “Hello, Spring Boot!” ought to appear.

That’s it! Your first basic Spring Boot web application has been constructed and launched.

Recommended: Java course in Chennai.

Core Spring Boot Concepts

Here are the core Spring Boot concepts:

  • Starters: Dependency descriptors known as “starters” group related technologies together.
    • For example, dependencies for creating web applications (Tomcat, Spring MVC, etc.) are included in spring-boot-starter-web.
      • Starters make your build.gradle (for Gradle) or pom.xml (for Maven) simpler.
  • Auto-Configuration: Using the dependencies you’ve supplied, Spring Boot automatically sets up your application.
    • It eliminates the need for explicit configuration by automatically estimating the beans you require and configuring them for you.
  • Spring Boot CLI (Command Line Interface): A command-line tool enables you to rapidly prototype Spring applications.
    • Without the usual project structure setup, you can instantly start up applications and run Groovy scripts.
  • Actuator: Offers production-ready capabilities via JMX or HTTP endpoints, including health checks, metrics, and information.
    • In a production setting, this aids in application management and monitoring.
  • Embedded Servers: To make your application a self-contained executable, Spring Boot can embed web servers such as Tomcat, Jetty, or Undertow straight into the JAR file.
  • Spring Application Context: The foundation of a Spring application, the Application Context is built upon by Spring Boot and serves to manage beans and their dependencies.
  • Properties and Configuration: Using properties files (application.properties or application.yml), environment variables, command-line arguments, and other tools, Spring Boot facilitates the management of application configuration.

Related: Struts Training in Chennai.

Building RESTful APIs in Spring

Let’s go over using Spring Boot to create RESTful APIs. Because of its interaction with Spring MVC, Spring Boot makes this very simple.

The following are the primary concepts and procedures:

  • Dependencies: The spring-boot-starter-web requirement is usually required in your build.gradle or pom.xml file. This includes an embedded web server (such as Tomcat) and Spring MVC.
  • Controllers: @RestController annotations are used while creating Java classes. @Controller and @ResponseBody are combined in this annotation.
    • @Controller signifies that web requests are handled by the class.
    • @ResponseBody instructs that the methods’ return value be sent straight to the HTTP response body, which is frequently in the form of XML or JSON.
  • Request Mappings: You can map URL routes and HTTP request methods (GET, POST, PUT, DELETE) to certain handler methods in your controller by using annotations such as @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @RequestMapping.
  • Path Variables: By including the @PathVariable annotation in your method arguments, you can retrieve values from the URL path. /users/{id}, for instance, where {id} is a path variable.
  • Request Parameters: The @RequestParam annotation in your method parameters (e.g., /users?name=John) allows you to retrieve query parameters from the URL.
  • Request Body: The @RequestBody annotation allows you to retrieve the data sent in the request body (often in JSON) for methods like POST and PUT. If the necessary dependency is present, Spring uses Jackson to handle the conversion automatically (for JSON by default).
  • HTTP Status Codes: ResponseEntity lets you specify both the content and the HTTP status code of the response, so you may manage the latter.

Example:

package com.example.demo;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

import java.util.List;

import java.util.NoSuchElementException;

@RestController

@RequestMapping(“/api/users”)

public class UserController {

    private List<User> users = new ArrayList<>();

    private int nextId = 1;

    @GetMapping

    public List<User> getAllUsers() {

        return users;

    }

    @GetMapping(“/{id}”)

    public ResponseEntity<User> getUserById(@PathVariable int id) {

        return users.stream()

                .filter(user -> user.getId() == id)

                .findFirst()

                .map(ResponseEntity::ok)

                .orElse(ResponseEntity.notFound().build());

    }

    @PostMapping

    @ResponseStatus(HttpStatus.CREATED)

    public User createUser(@RequestBody User newUser) {

        newUser.setId(nextId++);

        users.add(newUser);

        return newUser;

    }

    @PutMapping(“/{id}”)

    public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User updatedUser) {

        for (int i = 0; i < users.size(); i++) {

            if (users.get(i).getId() == id) {

                updatedUser.setId(id);

                users.set(i, updatedUser);

                return ResponseEntity.ok(updatedUser);

            }

        }

        return ResponseEntity.notFound().build();

    }

    @DeleteMapping(“/{id}”)

    @ResponseStatus(HttpStatus.NO_CONTENT)

    public void deleteUser(@PathVariable int id) {

        users.removeIf(user -> user.getId() == id);

    }

}

class User {

    private int id;

    private String name;

    // Constructors, Getters, and Setters (omitted for brevity)

    public User() {}

    public User(String name) {

        this.name = name;

    }

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

}

  • /api/users with GET returns all users.
  • /api/users/{id} with GET returns a specific user.
  • /api/users with POST creates a new user (data in the request body).
  • /api/users/{id} with PUT updates an existing user.
  • /api/users/{id} with DELETE deletes a user.

Related: Hibernate Training in Chennai.

Data Persistence with Spring Boot

Through the Spring Data project, Spring Boot offers first-rate support for data persistence. It makes working with different databases easier. These are the common approaches: 

Spring Data JPA (Java Persistence API):

A JPA provider abstraction (e.g., Hibernate, EclipseLink). The boilerplate code required for data access is significantly reduced.

Key Components of Spring Data JPA:

Here are the components of Spring Data JPA:

  • Entities: They are Java classes that represent database tables and are annotated with @Entity.
  • Repositories: Interfaces that extend JpaRepository (or equivalent interfaces for Spring Data repositories) are called repositories. Using method naming standards, Spring Data automatically creates the implementation for common CRUD (Create, Read, Update, Delete) activities. 
  • Dependency: spring-boot-starter-data-jpa   

Spring Data JDBC:

It offers a more straightforward method of using JDBC to communicate with relational databases. It has the advantages of Spring Data repositories but is more akin to ordinary JDBC than JPA.

Key Components of Spring Data JDBC:

Here are the major components of Spring Data JDBC:

  • Entities: Database tables that are mapped to simple Java objects (POJOs).
  • Repositories: Interfaces that extend PagingAndSortingRepository or CrudRepository. Usually, you use the mapping features of Spring Data JDBC or write extra SQL.
  • Dependency: spring-boot-starter-data-jdbc

Spring Data MongoDB:

It allows for integration with the NoSQL document database MongoDB. 

Key Components of Spring Data MongoDB:

Here are the key components of Spring Data MongoDB:

  • Documents: MongoDB documents are represented using Java classes called documents, which are frequently annotated with @Document.
  • Repositories: MongoRepository-extending interfaces.

Dependency: spring-boot-starter-data-mongodb

Other Spring Data Projects: 

Through their individual Spring Data projects, Spring Boot also supports additional NoSQL databases, including Redis, Cassandra, Neo4j, and others. 

Step 1: Add the JPA Dependency:

    <dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency> 

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

</dependency> 

Step 2: Create an Entity:

package com.example.demo;

import jakarta.persistence.Entity;

import jakarta.persistence.GeneratedValue;

import jakarta.persistence.GenerationType;

import jakarta.persistence.Id;

@Entity

public class User {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    private String name;

    private String email;

    // Constructors, Getters, and Setters (omitted)

    public User() {}

    public User(String name, String email) {

        this.name = name;

        this.email = email;

    }

    // Getters and Setters

    public Long getId() {

        return id;

    }

    public void setId(Long id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

}

Step 3: Create a Repository

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> {

    List<User> findByName(String name);

    User findByEmail(String email);

}

Save(), findById(), findAll(), deleteById(), and other methods are automatically provided by JpaRepository. Additionally, by using naming conventions (such as findByName), you can construct bespoke query methods.

Step 4: Use the Repository in your Service or Controller:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class UserService {

    @Autowired

    private UserRepository userRepository;

    public void createUser(String name, String email) {

        userRepository.save(new User(name, email));

    }

    public List<User> getUsersByName(String name) {

        return userRepository.findByName(name);

    }

    public User getUserByEmail(String email) {

        return userRepository.findByEmail(email);

    }

    public List<User> getAllUsers() {

        return userRepository.findAll();

    }

}

Based on your dependencies and properties (such as the database URL, username, and password in application.properties or application.yml), Spring Boot automatically configures the data source.

Recommended: J2EE training in Chennai.

Handling Data with Forms in Spring Boot

Spring MVC and its data binding features are used when handling data from HTML forms in Spring Boot.

Create a Model (POJO): The data you anticipate receiving from the form will be represented by a Java class.

public class FormData {

    private String name;

    private String email;

    // Getters and Setters

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

}

Create a Controller to Display the Form: To handle the request for the HTML form, you will require a controller function. To enable form fields to be tied to the view, you may pass an empty instance of your model.

@Controller

public class FormController {

    @GetMapping(“/form”)

    public String showForm(Model model) {

        model.addAttribute(“formData”, new FormData()); // Add an empty FormData object to the model

        return “form”; // Name of your HTML form template

    }

}

“`

Create the HTML Form: The input fields in your HTML form will have name attributes that match those of the fields in your FormData class. For simple data binding, you’ll usually utilize Thymeleaf, a template engine frequently used with Spring Boot.

<!DOCTYPE HTML>

<html xmlns:th=”http://www.thymeleaf.org”>

<head>

    <title>Form</title>

</head>

<body>

    <h1>Enter Information</h1>

    <form action=”/processForm” method=”post” th:object=”${formData}”>

        <div>

            <label for=”name”>Name:</label>

            <input type=”text” id=”name” th:field=”*{name}”/>

        </div>

        <div>

            <label for=”email”>Email:</label>

            <input type=”email” id=”email” th:field=”*{email}”/>

        </div>

        <button type=”submit”>Submit</button>

    </form>

</body>

</html>

  • th:object=”${formData}”: This connects the form to the model’s formData object.
  • th:field=”*{name}”: This links the input field named “name” to the formData object’s name property.

Create a Controller to Process the Form Submission: When the form is submitted, a different controller function will be required to handle the POST request. If the field names match, Spring will automatically link the form data to an instance of your model class.

@Controller

public class FormProcessingController {

    @PostMapping(“/processForm”)

    public String processForm(@ModelAttribute FormData formData, Model model) {

        System.out.println(“Received data: Name=” + formData.getName() + “, Email=” + formData.getEmail());

        model.addAttribute(“formData”, formData); // Optionally pass the received data to a result page

        return “result”; // Name of your result HTML template

    }

}

“`

* `@ModelAttribute FormData formData`: This annotation tells Spring to create an instance of `FormData` and bind the incoming form parameters (with names “name” and “email”) to the corresponding properties of this object.

Create a Result Page: To show the data that has been submitted, you can make an HTML page.

<!DOCTYPE HTML>

<html xmlns:th=”http://www.thymeleaf.org”>

<head>

    <title>Result</title>

</head>

<body>

    <h1>Submitted Information</h1>

    <p th:text=”‘Name: ‘ + ${formData.name}”></p>

    <p th:text=”‘Email: ‘ + ${formData.email}”></p>

    <a href=”/form”>Go back to the form</a>

</body>

</html>

Recommended: Advanced Java Training in Chennai.

Validation in Spring Boot

Spring Boot effortlessly interacts with Spring MVC and offers strong support for data validation via the Bean Validation API (JSR-380). Here’s how implement validation:

Add the Validation Starter Dependency: Add the spring-boot-starter-validation dependency to your build.gradle or pom.xml file if you haven’t previously.

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-validation</artifactId>

</dependency> 

Annotate Your Model: Annotations from the jakarta.validation.constraints package are used to provide validation rules for your fields in your data model class (the one to which you are binding form data or request bodies).

import jakarta.validation.constraints.Email;

import jakarta.validation.constraints.NotBlank;

import jakarta.validation.constraints.Size;

public class FormData {

    @NotBlank(message = “Name cannot be blank”)

    @Size(min = 2, max = 100, message = “Name must be between 2 and 100 characters”)

    private String name;

    @NotBlank(message = “Email cannot be blank”)

    @Email(message = “Invalid email format”)

    private String email;

    // Getters and Setters

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

}

Common validation annotations include:
  • @NotBlank: Verifies that, following trimming, the annotated string is neither null nor empty.
  • @NotEmpty: Verifies that the annotated array, map, collection, or string is not empty or null.
  • @Size: Verifies that the size of the annotated string, collection, map, or array falls between the given minimum and maximum values.
  • @Min, @Max: Verifies that the number that has been annotated is more than, equal to, or less than the given value.
  • @Email: Verifies that the string with annotations is a valid email address.
  • @Pattern: Verifies that the given regular expression matches the annotated string.

Trigger Validation in Your Controller: You must annotate the method parameter that accepts the model object with @Valid in order to initiate the validation. 

  • The validation will then be carried out automatically by Spring. 
  • A BindingResult object that comes right after the @Valid parameter in the method signature contains the validation results.

For Form Data:

import jakarta.validation.Valid;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.PostMapping;

@Controller

public class FormValidationController {

    @GetMapping(“/form”)

    public String showForm(Model model) {

        model.addAttribute(“formData”, new FormData());

        return “form”;

    }

    @PostMapping(“/processForm”)

    public String processForm(@Valid @ModelAttribute FormData formData, BindingResult result, Model model) {

        if (result.hasErrors()) {

            // If there are validation errors, return to the form

            return “form”;

        }

        // Process the valid form data

        System.out.println(“Received valid data: Name=” + formData.getName() + “, Email=” + formData.getEmail());

        model.addAttribute(“formData”, formData);

        return “result”;

    }

}

For RESTful APIs (Request Body):

import jakarta.validation.Valid;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RestController;

import java.util.stream.Collectors;

@RestController

public class ApiValidationController {

    @PostMapping(“/api/data”)

    public ResponseEntity<?> processData(@Valid @RequestBody FormData formData, BindingResult result) {

        if (result.hasErrors()) {

            List<String> errors = result.getFieldErrors().stream()

                    .map(error -> error.getField() + “: ” + error.getDefaultMessage())

                    .collect(Collectors.toList());

            return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);

        }

        // Process the valid data

        return ResponseEntity.ok(“Data processed successfully: ” + formData.getName());

    }

}

Displaying Validation Errors in the View (for Forms): You may quickly show validation problems in your HTML form by using Thymeleaf.

<!DOCTYPE HTML>

<html xmlns:th=”http://www.thymeleaf.org”>

<head>

    <title>Form</title>

</head>

<body>

    <h1>Enter Information</h1>

    <form action=”/processForm” method=”post” th:object=”${formData}”>

        <div>

            <label for=”name”>Name:</label>

            <input type=”text” id=”name” th:field=”*{name}”/>

            <p th:if=”${#fields.hasErrors(‘name’)}” th:errors=”*{name}” style=”color:red;”></p>

        </div>

        <div>

            <label for=”email”>Email:</label>

            <input type=”email” id=”email” th:field=”*{email}”/>

            <p th:if=”${#fields.hasErrors(’email’)}” th:errors=”*{email}” style=”color:red;”></p>

        </div>

        <button type=”submit”>Submit</button>

    </form>

</body>

</html>

  • th:if=”${#fields.hasErrors(‘name’)}”: Verifies whether the ‘name’ field contains any errors.
  • th:errors=”*{name}”: Shows the ‘name’ field’s validation error message or messages.

Explore all software training courses at SLA.

Conclusion

While this Spring Boot Tutorial for Beginners provides a foundation, the world of Spring Boot is vast and offers much more! You can explore topics like security, advanced data management, testing, and building microservices through our Spring Boot Training in Chennai.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.