Setting Up A Java 21 + Spring Boot Project

Alex Johnson
-
Setting Up A Java 21 + Spring Boot Project

Hey guys! Let's dive into setting up a new Java 21 project with Spring Boot, using Maven as our build tool. This is a crucial first step for any Java application, ensuring we have a solid foundation to build upon. We'll cover everything from creating the basic project structure to setting up essential configuration files. So, buckle up, and let’s get started!

Why Java 21 and Spring Boot?

Before we jump into the how-to, let’s quickly touch on why Java 21 and Spring Boot are a fantastic combo. Java 21, the latest long-term support (LTS) version, brings a plethora of performance improvements, new features, and enhanced security. It’s like giving your project a supercharged engine! Spring Boot, on the other hand, simplifies the development of Java applications by providing sensible defaults and auto-configuration. Think of it as the smart assistant that handles the boilerplate, so you can focus on the actual business logic. Together, they make for a powerful and efficient development experience.

Key Benefits of Java 21

Java 21 introduces several key improvements that can significantly benefit your projects:

  • Virtual Threads: These lightweight threads drastically reduce the overhead of concurrency, allowing you to handle more concurrent tasks with fewer resources. This is a game-changer for applications that need to manage many concurrent connections or processes.
  • Pattern Matching for Switch: Simplifies complex conditional logic, making your code cleaner and more readable. Instead of writing lengthy if-else chains, you can use pattern matching to handle different cases more elegantly.
  • Record Patterns: Enhances data navigation and processing by allowing you to deconstruct record objects directly in patterns. This makes working with immutable data structures more straightforward and less verbose.
  • Sequenced Collections: Introduces a new interface for collections that have a defined encounter order, making operations like first(), last(), and reversed() more efficient and predictable.
  • Foreign Function & Memory API: Improves interoperability with non-Java code and native libraries, opening doors to more efficient memory management and system interactions.

These features not only make your code more performant but also contribute to better maintainability and scalability.

Why Spring Boot is a Game-Changer

Spring Boot truly shines when it comes to streamlining Java application development. Here’s why it’s a game-changer:

  • Auto-Configuration: Spring Boot automatically configures your application based on the dependencies you add. It intelligently sets up the beans and configurations needed, reducing the need for manual setup.
  • Embedded Servers: Spring Boot comes with embedded servers like Tomcat, Jetty, and Undertow, making it incredibly easy to deploy your application without needing to configure a separate server environment.
  • Starter Dependencies: Spring Boot starters bundle related dependencies together, simplifying your Maven or Gradle configuration. For example, the spring-boot-starter-web dependency includes everything you need to build a web application.
  • Actuator: Provides production-ready features like health checks, metrics, and auditing out of the box, giving you insights into your application's performance and health.
  • Simplified Configuration: Spring Boot uses application.properties or application.yml files for configuration, which are much easier to manage than traditional XML configurations.

By leveraging these features, you can significantly reduce development time and focus on building the core functionality of your application. Spring Boot eliminates much of the boilerplate, allowing you to get a working application up and running quickly.

1. Setting Up the Basic Project Structure

Alright, let’s get our hands dirty! The first step is to create the basic directory structure for our project. This will help us keep our code organized and maintainable from the get-go. We’ll be using Maven, so our project structure will follow the standard Maven conventions.

Creating the Project Directory

First things first, let's create the main project directory. You can name it whatever you like, but something descriptive like my-java21-springboot-app works well. Open your terminal and navigate to the directory where you want to create your project, then run:

mkdir my-java21-springboot-app
cd my-java21-springboot-app

Generating the Maven Project

Next, we’ll use Maven to generate the basic project structure. Maven’s archetype:generate goal will set up the standard directory layout and create a basic pom.xml file. Run the following command:

mvn archetype:generate \
    -DgroupId=com.example \
    -DartifactId=my-java21-springboot-app \
    -DarchetypeArtifactId=maven-archetype-quickstart \
    -DinteractiveMode=false

This command does the following:

  • -DgroupId: Sets the group ID for your project (e.g., com.example).
  • -DartifactId: Sets the artifact ID for your project (e.g., my-java21-springboot-app).
  • -DarchetypeArtifactId: Specifies the Maven archetype to use. maven-archetype-quickstart is a basic archetype for simple projects.
  • -DinteractiveMode=false: Runs Maven in non-interactive mode, so it doesn’t prompt for input.

After running this command, Maven will create a basic project structure with a pom.xml file and source directories.

Adding Spring Boot Dependencies

Now, let’s add the necessary Spring Boot dependencies to our pom.xml file. Open pom.xml in your favorite text editor and add the following dependencies inside the <dependencies> tag:

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

Replace YOUR_SPRING_BOOT_VERSION with the version of Spring Boot you want to use (e.g., 3.2.0).

We’ve added two dependencies here:

  • spring-boot-starter-web: This starter includes everything we need to build a web application, including Spring MVC, Tomcat, and Jackson for JSON processing.
  • spring-boot-starter-test: This starter provides testing dependencies like JUnit, Mockito, and Spring Test.

Adding the Spring Boot Maven Plugin

To make our project a Spring Boot application, we need to add the Spring Boot Maven plugin. Add the following plugin configuration inside the <build> tag in your pom.xml:

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

Again, replace YOUR_SPRING_BOOT_VERSION with the appropriate version.

2. Creating the Main Packages

Next up, we'll create the main packages that will house our application's components. This structured approach will help keep our codebase organized and maintainable as the project grows. We'll be creating packages for controllers, services, repositories, and models. Think of these as the different departments in our application's office, each with its own specific responsibilities.

Controller Package

The controller package will contain our REST controllers. Controllers are the entry points for our application, handling incoming HTTP requests and routing them to the appropriate service. They act as the traffic cops of our application, directing requests to the right place.

Service Package

The service package will house our business logic. Services perform the core operations of our application, such as data processing, validation, and interaction with other services or repositories. This is where the real work happens – the engine room of our application.

Repository Package

The repository package will contain our data access components. Repositories are responsible for interacting with the database, performing CRUD operations (Create, Read, Update, Delete), and handling data persistence. They are the data librarians of our application, managing the storage and retrieval of information.

Model Package

The model package will hold our data models or entities. Models represent the structure of our data, defining the properties and relationships of our objects. Think of them as the blueprints for our data, defining what information we're working with.

Creating the Package Structure

To create these packages, navigate to the src/main/java directory in your project. You'll find a directory corresponding to your groupId (e.g., com/example). Inside this directory, create the following packages:

  • controller
  • service
  • repository
  • model

You can create these packages manually using your file explorer or use the following commands in your terminal:

mkdir -p src/main/java/com/example/controller
mkdir -p src/main/java/com/example/service
mkdir -p src/main/java/com/example/repository
mkdir -p src/main/java/com/example/model

Replace com/example with your actual groupId.

With these packages in place, our project structure is starting to take shape. We're setting the stage for a well-organized and maintainable application.

3. Adding .gitignore and README.md

Now, let's add some essential files to our project: .gitignore and README.md. These files are crucial for version control and project documentation. Think of .gitignore as the bouncer for our Git repository, deciding which files to keep out, while README.md is the welcome mat, providing essential information about our project.

Creating .gitignore

The .gitignore file specifies intentionally untracked files that Git should ignore. This is super important for excluding things like compiled bytecode, IDE configuration files, and other files that shouldn't be committed to the repository. Keeping these files out of the repository helps maintain a clean and efficient version control history.

Create a new file named .gitignore in the root of your project and add the following common entries:

# Compiled Java class files
*.class

# Log file
*.log

# Package Files #
*.jar
*.war
*.ear

# Maven #
target/

# Intellij files #
.idea/

# Eclipse files #
.settings/
.project

# Spring files
.mvnw
.mvnw.cmd

This .gitignore file excludes compiled Java class files, log files, packaged archives (JAR, WAR, EAR), Maven's target directory, IntelliJ IDEA and Eclipse IDE configuration files, and Spring-related files. You can customize this file further based on your specific project needs.

Creating README.md

The README.md file is a markdown file that provides an overview of your project. It's the first thing people see when they visit your project's repository, so it's essential to make it informative and engaging. A good README.md should include:

  • Project title and description
  • How to build and run the project
  • Dependencies and requirements
  • Usage instructions
  • License information
  • Contact information

Create a new file named README.md in the root of your project and add some basic information:

# My Java 21 Spring Boot App

A simple Java 21 application built with Spring Boot.

## Getting Started

These instructions will get you a copy of the project up and running on your local machine.

### Prerequisites

*   Java 21
*   Maven

### Building the Project

```bash
mvn clean install

Running the Application

mvn spring-boot:run

Dependencies

  • Spring Boot
  • Maven

Usage

[Add usage instructions here]

License

[Add license information here]

Contact

[Your Name] - [Your Email]


You can expand this `README.md` file with more details as your project evolves. A well-crafted `README.md` can significantly improve the usability and visibility of your project.

## 4. Configuring Initial `application.yml`

Now, let’s set up our initial `application.yml` file. This file is where we'll configure our Spring Boot application, setting properties like the server port, database connections, and logging levels. Think of it as the application's control panel, allowing us to tweak various settings without modifying our code.

### Why `application.yml`?

Spring Boot supports both `application.properties` and `application.yml` for configuration. `application.yml` is often preferred because it uses YAML (YAML Ain't Markup Language), which is more human-readable and allows for hierarchical configuration. This makes it easier to organize and manage complex configurations.

### Creating `application.yml`

Create a new directory `src/main/resources` if it doesn't already exist. Inside this directory, create a new file named `application.yml`. This is where we'll store our application's configuration properties.

### Basic Configuration

Let's start with some basic configurations. We'll set the server port and a simple application name. Add the following content to your `application.yml` file:

```yaml
spring:
  application:
    name: my-java21-springboot-app

server:
  port: 8080

Here’s what these properties do:

  • spring.application.name: Sets the name of our application. This name is used in log messages and other contexts.
  • server.port: Sets the port on which our application will run. We’ve set it to 8080, which is a common default.

Adding Logging Configuration

Configuring logging is essential for monitoring and debugging our application. Let's add some logging configuration to our application.yml file:

logging:
  level:
    root: INFO
    com.example: DEBUG

These properties configure the logging levels:

  • logging.level.root: Sets the root logging level to INFO. This means that log messages with a level of INFO or higher (e.g., WARN, ERROR) will be displayed.
  • logging.level.com.example: Sets the logging level for our com.example package (and its subpackages) to DEBUG. This allows us to see more detailed log messages for our application's code.

Adding Database Configuration (Example)

If your application needs to connect to a database, you can configure the connection properties in application.yml. Here’s an example of configuring a connection to a PostgreSQL database:

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: myuser
    password: mypassword
  jpa:
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect

These properties configure the database connection:

  • spring.datasource.url: Specifies the JDBC URL for the database.
  • spring.datasource.username: Sets the username for the database connection.
  • spring.datasource.password: Sets the password for the database connection.
  • spring.jpa.hibernate.ddl-auto: Configures Hibernate to automatically update the database schema.
  • spring.jpa.properties.hibernate.dialect: Specifies the database dialect for Hibernate.

Remember to replace the example values with your actual database credentials and settings.

Conclusion

And there you have it! We’ve successfully set up a new Java 21 project with Spring Boot, created the basic project structure, added essential files like .gitignore and README.md, and configured our initial application.yml file. This is a fantastic starting point for building robust and scalable Java applications. Keep up the great work, and happy coding!

To deepen your understanding of Spring Boot and best practices, consider exploring the official Spring Boot documentation. It's a treasure trove of information and examples that can help you become a Spring Boot pro!

You may also like