Building Your First Spring Boot Application with Java

Introduction

An open-source Java framework called Spring Boot is used to build production-quality, stand-alone Spring apps with little setup. Spring Boot, created to streamline the intricate setups needed for conventional Spring applications, has gained popularity among developers for creating cutting-edge, scalable online apps.


Everything from setup to deployment will be covered in this tutorial as you create your first Spring Boot application. You will have a working Spring Boot application and a better grasp of its features and advantages by the end of this blog.

Table of Contents

  1. What is Spring Boot?
  2. Prerequisites
  3. Setting Up the Environment
  4. Creating a New Spring Boot Project
  5. Understanding the Project Structure
  6. Building a Simple REST API
  7. Running the Application
  8. Testing the Application
  9. Deploying the Application
  10. Advanced Features in Spring Boot
  11. Troubleshooting Common Issues
  12. Conclusion

What is Spring Boot?

Building Java applications is made easier with Spring Boot, an addition to the Spring Framework. It speeds up and improves development by getting rid of boilerplate code and setups.

Key Features:

  • Auto-Configuration: Automatically configures Spring applications based on the included dependencies.
  • Embedded Server: Includes an embedded Tomcat, Jetty, or Undertow server for running applications without external setups.
  • Production-Ready Features: Provides metrics, health checks, and externalized configurations for enterprise-ready applications.
  • Starter Dependencies: Simplifies dependency management by bundling commonly used libraries into a single dependency.

Prerequisites

Before you begin, ensure you have the following:

  • Java Development Kit (JDK): Version 8 or higher.
  • Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or Visual Studio Code.
  • Maven or Gradle: Build tools for managing project dependencies.
  • Basic Java Knowledge: Familiarity with Java syntax and concepts like classes and methods.

Setting Up the Environment

Step 1: Install JDK

Download and install the latest JDK from Oracle or OpenJDK. Set the JAVA_HOME environment variable to point to the JDK installation directory.

Step 2: Install Maven or Gradle

Install Maven from Maven’s official website or Gradle from Gradle’s official website. Verify the installation by running mvn -v or gradle -v in the terminal.

Step 3: Install an IDE

Download and install an IDE like IntelliJ IDEA or Eclipse.

Creating a New Spring Boot Project

Step 1: Use Spring Initializr

Spring Initializr is a web-based tool for generating Spring Boot projects. Access it at https://start.spring.io/.

  1. Select Project: Maven or Gradle.
  2. Language: Java.
  3. Spring Boot Version: Choose the latest stable version.
  4. Dependencies: Add Spring Web and Spring Boot DevTools.
  5. Generate Project: Click “Generate” to download the project as a ZIP file.

Step 2: Import the Project

  1. Extract the ZIP file.
  2. Open your IDE and import the project as a Maven or Gradle project.
  3. Wait for the IDE to resolve dependencies.

Understanding the Project Structure

A typical Spring Boot project has the following structure:

src/main/java
    com.example.demo
        DemoApplication.java
src/main/resources
    application.properties
pom.xml (or build.gradle)

Key Files:

  • DemoApplication.java: The main entry point of the application.
  • application.properties: Used for configuring the application.
  • pom.xml or build.gradle: Manages project dependencies.

Building a Simple REST API

Step 1: Create a Controller Class

In the com.example.demo package, create a new class named HelloController:

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 sayHello() {
        return "Hello, Spring Boot!";
    }
}

Step 2: Configure the Application

Open application.properties and add the following (optional):

server.port=8080

This sets the server port to 8080.

Running the Application

Step 1: Run the Main Class

Run the DemoApplication.java file:

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

Step 2: Access the API

Open a web browser or Postman and visit: http://localhost:8080/hello. You should see the response: Hello, Spring Boot!.

Testing the Application

Step 1: Add Unit Tests

Create a test class HelloControllerTest:

package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
class HelloControllerTest {
    @Test
    void testHelloEndpoint() {
        HelloController controller = new HelloController();
        String response = controller.sayHello();
        assertThat(response).isEqualTo("Hello, Spring Boot!");
    }
}

Run the tests using your IDE or the command line (mvn test or gradle test).

Advanced Features in Spring Boot

1. Database Integration

Relational databases such as PostgreSQL, H2, and MySQL may be seamlessly integrated with Spring Boot. Configure the database properties in application.properties and add the required dependencies to your pom.xml or build.gradle file.

Example:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update

Use Spring Data JPA to create repositories and interact with the database effortlessly.

Sample Repository:

package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}

2. Spring Security

Spring Security adds authentication and authorization features to your application. Add the spring-boot-starter-security dependency and configure security settings in your application.

Example:

package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/hello").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

3. Actuator

Spring Boot Actuator provides insights into the application’s health and metrics. Add the spring-boot-starter-actuator dependency and access endpoints like /actuator/health.

Troubleshooting Common Issues

1. Port Already in Use

If you encounter a port already in use error, change the server port in application.properties:

server.port=8081

2. Dependency Conflicts

Ensure your pom.xml or build.gradle does not have conflicting dependencies. Use the mvn dependency:tree command to analyze dependencies.

3. Application Fails to Start

Check the logs for stack traces. Common issues include missing properties in application.properties or incorrect dependency versions.

Deploying the Application

Step 1: Build the Application

Use Maven or Gradle to package the application:

mvn clean package

This creates a JAR file in the target directory.

Step 2: Run the JAR File

Run the JAR file:

java -jar target/demo-0.0.1-SNAPSHOT.jar

Step 3: Deploy to a Server

Deploy the JAR file to a cloud provider or containerize the application using Docker for deployment.

Dockerfile Example:

FROM openjdk:11
COPY target/demo-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]

Conclusion

The process of creating a Spring Boot application is simple and makes use of strong capabilities to streamline development. You have learned how to launch, test, and deploy a Spring Boot application and have developed a working REST API by following this tutorial.


Building enterprise-grade apps with little effort is made possible by Spring Boot. To realize its full potential, keep investigating sophisticated features like messaging, security, and database integration.

For More Info Visit: Java Training in Vizag

Leave a Comment

Your email address will not be published. Required fields are marked *