Bootstrap Spring Boot 3 Project With JDK 21: A Quick Guide

by Alex Johnson 59 views

Embarking on a new project can be both exciting and daunting. This guide walks you through setting up a Spring Boot 3.x project using JDK 21, establishing a solid foundation for your application. We'll cover everything from initializing the project and setting up version control to configuring essential dependencies and ensuring your first REST endpoint returns a successful 200.

Initializing a New Spring Boot 3.x Project with JDK 21

Starting with a clean slate is crucial. To initialize your new Spring Boot project, ensure you have JDK 21 installed. You can verify your Java version by running java -version in your terminal. Next, you can use Spring Initializr (either via the web interface at start.spring.io or through your IDE) to generate the basic project structure. When using Spring Initializr, make sure to select:

  • Project Type: Maven or Gradle (whichever you prefer)
  • Language: Java
  • Spring Boot Version: 3.x (the latest stable release)
  • Group: Your organization's group ID (e.g., com.example)
  • Artifact: Your project's name (e.g., my-app)
  • Packaging: Jar or War (depending on your deployment needs)
  • Java: 21

Once you've configured these settings, download the generated project. Unzip it to your desired location. This provides a basic, runnable Spring Boot application skeleton, setting the stage for further customization and development.

Setting Up Project Structure and Version Control (Git)

With the project initialized, the next step is to organize the project structure and integrate it with a version control system. A well-structured project enhances maintainability and scalability. Typically, a Spring Boot project includes directories for main application code (src/main/java), resources (src/main/resources), test code (src/test/java), and static assets (src/main/resources/static).

Now, let's talk about version control. Git is indispensable for tracking changes, collaborating with others, and reverting to previous states. To set up Git, navigate to your project's root directory in the terminal and run the following commands:

git init
git add .
git commit -m "Initial commit: Project setup"

These commands initialize a new Git repository, add all files to the staging area, and create an initial commit with a descriptive message. It's also wise to create a .gitignore file to exclude unnecessary files (like .idea/, target/, and .DS_Store) from version control. Services like GitHub, GitLab, or Bitbucket are perfect for hosting your remote repository, facilitating collaboration and providing backup.

Adding Basic Dependencies

Dependencies are the lifeblood of any modern application, bringing in pre-built functionality and saving development time. In this project, we'll add several key dependencies to our pom.xml (if you're using Maven) or build.gradle (if you're using Gradle) file. These dependencies include:

  • Spring Web: For building RESTful web applications.
  • Spring Data JPA: For simplifying database access using the Java Persistence API.
  • PostgreSQL Driver: For connecting to a PostgreSQL database.
  • Liquibase: For database schema management and migrations.
  • Hibernate Envers: For auditing data changes.
  • Keycloak Adapter: For integrating with Keycloak for authentication and authorization.

Here's how you can add these dependencies using Maven:

<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>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.liquibase</groupId>
        <artifactId>liquibase-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-envers</artifactId>
    </dependency>
    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

And here's how to add them using Gradle:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'org.postgresql:postgresql'
    implementation 'org.liquibase:liquibase-core'
    implementation 'org.hibernate:hibernate-envers'
    implementation 'org.keycloak:keycloak-spring-boot-starter'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

After adding these dependencies, ensure to refresh your project's dependencies. In IntelliJ IDEA, you can do this by clicking the Maven or Gradle icon and selecting "Reload Project." This ensures that all the necessary libraries are downloaded and available for use in your project.

Configuring application.properties/yml for Environment Separation

Environment separation is vital for managing different configurations for development, testing, and production environments. Spring Boot makes this easy with application.properties or application.yml files. Create separate files for each environment, such as application-dev.properties, application-test.properties, and application-prod.properties.

In these files, you can define environment-specific properties, such as database connection details, API keys, and logging levels. For example:

application-dev.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=devuser
spring.datasource.password=devpassword
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

keycloak.auth-server-url=http://localhost:8080
keycloak.realm=myrealm
keycloak.resource=myclient

application-prod.properties:

spring.datasource.url=jdbc:postgresql://prod-db-server:5432/mydb
spring.datasource.username=produser
spring.datasource.password=prodpassword
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

keycloak.auth-server-url=https://auth.example.com
keycloak.realm=myrealm
keycloak.resource=myclient

To activate a specific environment, set the spring.profiles.active property in your main application.properties or application.yml file. For example:

spring.profiles.active=dev

This tells Spring Boot to load the properties from application-dev.properties in addition to the main configuration file. Using environment profiles ensures that your application behaves correctly in different deployment environments, avoiding configuration conflicts and streamlining the deployment process.

Preparing Initial README

A well-crafted README file is crucial for any project, serving as the first point of contact for developers and users. It should provide a concise overview of the project, its purpose, and instructions on how to set it up and run it. Your initial README should include:

  • Project Title and Description: A brief explanation of what the project does.
  • Prerequisites: List of software and tools required to run the project (e.g., JDK 21, Git, PostgreSQL).
  • Setup Instructions: Step-by-step guide on how to clone the repository, configure the environment, and build the project.
  • Running the Application: Instructions on how to start the Spring Boot application.
  • Example Usage: A simple example demonstrating how to interact with the application (e.g., making a request to a REST endpoint).
  • Contribution Guidelines: Information on how others can contribute to the project.
  • License Information: Details about the project's license.

Here's a basic example of a README file:

# My Spring Boot Application

A simple Spring Boot application built with JDK 21.

## Prerequisites

*   JDK 21
*   Git
*   PostgreSQL

## Setup Instructions

1.  Clone the repository:

    ```bash
    git clone https://github.com/your-username/my-app.git
    ```
2.  Configure the environment:

    *   Create a PostgreSQL database.
    *   Update `application-dev.properties` with your database credentials.
3.  Build the project:

    ```bash
    ./mvnw clean install
    ```

## Running the Application

```bash
./mvnw spring-boot:run

Example Usage

Send a GET request to http://localhost:8080/api/hello to see a greeting.

Contributing

Feel free to submit pull requests!

License

MIT


A well-documented README is essential for onboarding new team members and ensuring the long-term maintainability of your project. It should be kept up-to-date as the project evolves.

## Verifying Project Builds and Basic REST Endpoint

Finally, it's time to verify that your project builds successfully and that your basic REST endpoint returns a 200 OK status. First, build the project using Maven or Gradle:

```bash
./mvnw clean install   # Maven
./gradlew build        # Gradle

If the build is successful, you should see a BUILD SUCCESS message in the console. Next, run the Spring Boot application:

./mvnw spring-boot:run   # Maven
./gradlew bootRun        # Gradle

Once the application is running, create a simple REST controller with a basic endpoint. For example:

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

@RestController
public class HelloController {

    @GetMapping("/api/hello")
    public String hello() {
        return "Hello, World!";
    }
}

Now, open your web browser or use a tool like curl or Postman to send a GET request to http://localhost:8080/api/hello. If everything is configured correctly, you should receive a 200 OK response with the message "Hello, World!" in the body. This confirms that your project is set up correctly and that your REST endpoint is functioning as expected.

By following these steps, you've successfully bootstrapped a new Spring Boot 3.x project with JDK 21, configured essential dependencies, and verified that your initial setup is working correctly. This solid foundation sets the stage for building more complex features and functionalities in your application.

For more information on Spring Boot, visit the official Spring Boot documentation. Good luck!