Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

How to create a basic application in Java Spring Boot

Creating a basic Spring Boot application is a straightforward process, especially with the help of the Spring Initializr tool. Here's a step-by-step guide to creating a simple web application:

1. Bootstrap Your Project:

Using Spring Initializr:

  • Go to Spring Initializr.
  • Select your project type (Maven/Gradle) and language (Java/Kotlin/Groovy).
  • Fill in the project metadata as required.
  • Add the "Spring Web" dependency to include web capabilities.
  • Click "Generate" to download a zip file containing your new project.

Using IDE:

Many modern IDEs (like IntelliJ IDEA, Eclipse, and STS) have built-in support for bootstrapping a Spring Boot project using Spring Initializr.

2. Import the Project:

Extract the zip file you downloaded and open the project in your preferred IDE (IntelliJ IDEA, Eclipse, etc.).

3. Create a Controller:

To handle incoming HTTP requests, create a simple controller:

package com.example.demo.controller;

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

@RestController
public class HelloController {
    
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot!";
    }
}

4. Run Your Application:

Spring Boot applications contain an embedded Tomcat server, so you don't need to deploy your application to a separate server.

In the main class (named something like DemoApplication.java), there's a main method that starts the Spring Boot application:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Run this main method either directly from your IDE or from the command line using Maven or Gradle:

For Maven:

mvn spring-boot:run

For Gradle:

./gradlew bootRun

5. Test Your Application:

Once your application is running, open a web browser or use a tool like curl to access your endpoint:

http://localhost:8080/hello

You should see the message "Hello, Spring Boot!".

6. Further Customization:

From this basic setup, you can expand your application by:

  • Adding more dependencies like Spring Data JPA for database interactions.
  • Creating services, repositories, and other controllers as per your requirements.
  • Configuring application properties in the application.properties or application.yml file.

Spring Boot provides a lot of auto-configuration and sensible defaults, making it easy to get started and build robust applications.

  1. Building a Hello World application with Spring Boot:

    • Description: Create a minimal Spring Boot application with a "Hello, World!" endpoint.
    • Code:
      @RestController
      public class HelloWorldController {
      
          @GetMapping("/hello")
          public String sayHello() {
              return "Hello, World!";
          }
      }
      
  2. Creating a RESTful service in Java with Spring Boot:

    • Description: Develop a RESTful service using Spring Boot, complete with endpoints for various HTTP methods.
    • Code:
      @RestController
      @RequestMapping("/api")
      public class RestfulController {
      
          @GetMapping("/greet")
          public String greet() {
              return "Greetings!";
          }
      
          // Other RESTful endpoints
      }
      
  3. Configuring Spring Boot application properties for beginners:

    • Description: Configure application properties in a Spring Boot project, specifying settings like server port or database connection.
    • Code: Add properties to the application.properties or application.yml file.
      # application.properties
      server.port=8080
      
  4. Basic controller and request mapping in Spring Boot:

    • Description: Set up a basic controller with request mappings to handle incoming requests.
    • Code:
      @Controller
      public class BasicController {
      
          @RequestMapping("/welcome")
          public String welcome() {
              return "Welcome to Spring Boot!";
          }
      }
      
  5. Adding dependencies and dependencies management in Spring Boot:

    • Description: Add dependencies to your Spring Boot project using Maven or Gradle.
    • Code: Update the pom.xml or build.gradle file to include dependencies.
      <!-- Example for Maven -->
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
      </dependencies>
      
  6. Setting up a basic web application in Spring Boot:

    • Description: Configure a basic web application in Spring Boot with controllers and views.
    • Code: Create controllers, views, and templates for a simple web application.
      @Controller
      public class WebController {
      
          @GetMapping("/home")
          public String home() {
              return "index";
          }
      }
      
  7. Creating a simple data model in Spring Boot:

    • Description: Define a simple data model using entities or POJOs in a Spring Boot application.
    • Code:
      @Entity
      public class Item {
      
          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;
          private String name;
          // Other fields, getters, and setters
      }
      
  8. Handling static resources in a Spring Boot project:

    • Description: Configure Spring Boot to serve static resources like CSS, JavaScript, or images.
    • Code: Place static resources in the src/main/resources/static directory.
      <!-- Example usage in HTML -->
      <link rel="stylesheet" href="/css/style.css">
      
  9. Configuring logging in a basic Spring Boot application:

    • Description: Set up logging in a Spring Boot application using the built-in logging framework.
    • Code: Configure logging levels and outputs in the application.properties or application.yml file.
      # application.properties
      logging.level.root=INFO
      
  10. Adding database connectivity to a Spring Boot app:

    • Description: Integrate a database with a Spring Boot application using Spring Data JPA.
    • Code: Define entities, repositories, and configure database properties.
      @Entity
      public class User {
      
          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;
          private String username;
          private String email;
          // Other fields, getters, and setters
      }
      
  11. Configuring application profiles in Spring Boot:

    • Description: Configure application profiles to manage different environments (e.g., development, production).
    • Code: Define profiles in the application.properties or application.yml file.
      # application-dev.properties
      server.port=8081
      
  12. Implementing error handling in a Spring Boot project:

    • Description: Implement global error handling in a Spring Boot application to manage exceptions gracefully.
    • Code: Create an @ControllerAdvice class with exception handling methods.
      @ControllerAdvice
      public class GlobalExceptionHandler {
      
          @ExceptionHandler(Exception.class)
          public ResponseEntity<String> handleException(Exception e) {
              return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Something went wrong");
          }
      }
      
  13. Securing a basic Spring Boot application for beginners:

    • Description: Secure a Spring Boot application with basic authentication or authorization.
    • Code: Use Spring Security to configure authentication and authorization rules.
      @Configuration
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
      
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              http
                  .authorizeRequests()
                      .antMatchers("/public/**").permitAll()
                      .anyRequest().authenticated()
                  .and()
                  .formLogin().loginPage("/login").permitAll()
                  .and()
                  .logout().permitAll();
          }
      }
      
  14. Unit testing basics for Spring Boot applications:

    • Description: Write basic unit tests for Spring Boot components using JUnit and Mockito.
    • Code: Write test classes for controllers, services, and repositories.
      @RunWith(SpringRunner.class)
      @SpringBootTest
      public class MyServiceTest {
      
          @Autowired
          private MyService myService;
      
          @Test
          public void testSomething() {
              // Test logic
          }
      }