Write your first Spring Boot application

Jotty John - Jun 17 - - Dev Community

Creating a Spring Boot application involves several steps. Below is a guide to help you get started with a simple Spring Boot application:

Prerequisites
Java Development Kit (JDK): Ensure you have JDK 8 or later installed.
IDE: An Integrated Development Environment like IntelliJ IDEA, Eclipse, or VSCode.
Maven/Gradle: Build tools for managing project dependencies.

Step-by-Step Guide

1. Set Up Your Project
You can set up your project using Spring Initializr or manually.

Using Spring Initializr:

  • Go to Spring Initializr.

  • Select the following options:

    1. Project: Maven Project
    2. Language: Java
    3. Spring Boot: Latest stable version
    4. Project Metadata: Fill in Group, Artifact, and other details.
    5. Dependencies: Add dependencies like Spring Web, Spring Data
    JPA, H2 Database, etc.

  • Click on Generate to download the project as a zip file.

  • Unzip the file and open it in your IDE.

Manually:

  • Create a directory for your project.
  • Create a pom.xml file (for Maven) or build.gradle file (for Gradle).
  • Add the necessary Spring Boot dependencies.

Example pom.xml for Maven:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <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>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
Enter fullscreen mode Exit fullscreen mode

2. Create the Main Application Class
Create a main class annotated with @SpringBootApplication. This class will serve as the entry point for your application.

package com.demo.app;

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

@SpringBootApplication
public class SpringBootApp{
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Create a REST Controller
Create a simple REST controller to handle HTTP requests.

package com.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, World!";
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Configure Your Application
Configure your application properties. Open src/main/resources/application.properties and add any necessary configurations.

For example, to configure the H2 database:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Enter fullscreen mode Exit fullscreen mode

5. Run Your Application
You can run your application in several ways:

  • Using your IDE's run configuration.
  • Running the main method in DemoApplication.
  • Using Maven from the command line: mvn spring-boot:run.

6. Access Your Application
Once the application is running, you can access the REST endpoint in your browser or via curl/Postman:

http://localhost:8080/hello

Additional Features
Database Interaction: You can create entities and repositories to interact with a database.
Service Layer: Add services to handle business logic.
Exception Handling: Implement global exception handling using @ControllerAdvice.

Example of Adding a JPA Entity

package com.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    // getters and setters
}
Enter fullscreen mode Exit fullscreen mode

Example of a Repository

package com.demo.repo;

import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {
}
Enter fullscreen mode Exit fullscreen mode

Example of a Service

package com.demo.service;

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

import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Iterable<User> getAllUsers() {
        return userRepository.findAll();
    }

    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}
Enter fullscreen mode Exit fullscreen mode

Example of a Controller Using the Service

package com.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public Iterable<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id).orElseThrow(() -> new UserNotFoundException(id));
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}
Enter fullscreen mode Exit fullscreen mode

By following these steps, you can create a basic Spring Boot application. You can then extend it with more features as needed.

. . . . . . . . . . . . . . . . . . .
Terabox Video Player