Skip to content

Latest commit

 

History

History
594 lines (446 loc) · 21.3 KB

File metadata and controls

594 lines (446 loc) · 21.3 KB

Setting up the Spring Boot Project

1. Prerequisites

Ensure you have prepared your development environment as described in the preparation instructions.

2. Creating the Spring Boot Application

We’ll create a Spring Boot application using Spring Initializr. You can find the official Spring Boot documentation here: Spring Boot documentation.

Follow these steps to generate your project:

  1. Navigate to the Spring Initializr website: https://start.spring.io

  2. Configure the project with the following settings:

    Field Value

    Project

    Maven Project, you can see Maven and Alternatives for more details about Maven

    Language

    Java

    Spring Boot

    3.5.6

    Group

    com.capgemini.training

    Artifact

    appointment-booking

    Description

    Java Backend Developer Training

    Package name

    com.capgemini.training.appointmentbooking

    Packaging

    Jar

    Java

    21 (or your JDK version)

  3. Under Dependencies, add:

    Spring Boot Actuator

    Click the Generate button to download your project.

  4. Extract the downloaded project to a convenient location (e.g., C:\trainings\java-backend-developer)

  5. Build the project using Maven:

    mvn clean package
  6. Open the project in your IDE:

    For IntelliJ IDEA, use the following approach:

    Open in IntelliJ

2.1. Understanding the Project Structure

Examine the generated project structure. Spring Initializr has created a basic setup with the selected dependencies in the pom.xml file. Currently, you have 2 dependencies and 1 plugin:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </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>
Note

Think about it: Why do you think Spring Boot includes the test dependency by default? What does this tell us about Spring Boot’s philosophy regarding testing?

As you can see, the spring-boot-starter-test dependency has the scope set to test. This means that it will only be available during the test phase and will not be included in the final application package. For a quick overview of Maven configuration tags used in the pom.xml file—such as <scope>, <optional>, and <exclusions>—see Appendix: Key Maven Dependency Configuration Tags.

3. Configuring the Application

Add the following configuration to the application.properties file to enhance actuator endpoint visibility:

management.endpoint.health.show-components=always
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*

3.1. Understanding the Configuration

Let’s break down what each configuration property does:

  • management.endpoint.health.show-components=always - Shows health information for all components (databases, message queues, etc.) even when the application is healthy

  • management.endpoint.health.show-details=always - Displays detailed health information including disk space, database connectivity status, and custom health indicators

  • management.endpoints.web.exposure.include=* - Exposes all actuator endpoints via HTTP (by default, only /health and /info are exposed)

Warning

Exposing all actuator endpoints (*) should only be used in development environments. In production, you should explicitly specify which endpoints to expose for security reasons.

Note

Think about it: What security implications might arise from exposing all actuator endpoints in a production environment? How would you determine which endpoints are safe to expose?

4. Testing the Application

4.1. Running the Application

  1. Locate the AppointmentBookingApplication.java class and run it from your IDE, or use the Maven command:

    mvn spring-boot:run

    See 🆚 IntelliJ Run Config vs mvn spring-boot:run for a detailed comparison of IntelliJ and Maven run methods.

    Initially, you’ll see output similar to this:

    2025-10-14T14:00:14.128+02:00  INFO 35512 --- [appointment-booking] [           main] c.c.t.a.AppointmentBookingApplication    : Starting AppointmentBookingApplication using Java 21.0.3
    2025-10-14T14:00:14.131+02:00  INFO 35512 --- [appointment-booking] [           main] c.c.t.a.AppointmentBookingApplication    : No active profile set, falling back to 1 default profile: "default"
    2025-10-14T14:00:15.299+02:00  INFO 35512 --- [appointment-booking] [           main] c.c.t.a.AppointmentBookingApplication    : Started AppointmentBookingApplication in 1.641 seconds
    
    Process finished with exit code 0
  2. Try accessing http://localhost:8080/actuator/health - you’ll encounter a connection error:

    Unable to connect

4.2. Resolving the Web Server Issue

The application starts and immediately shuts down because it lacks a web server. Spring Boot applications without web capabilities exit after startup completion.

Solution: Add the Spring Web starter dependency to enable HTTP request handling:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Important

After modifying pom.xml:

  • IDE users: Sync Maven projects (see image below)

  • Command line users: Maven automatically uses the updated pom.xml

Sync maven changes

After adding the web dependency, restart the application. You should see:

2025-10-14T14:16:42.723+02:00  INFO 23176 --- [appointment-booking] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2025-10-14T14:16:42.736+02:00  INFO 23176 --- [appointment-booking] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2025-10-14T14:16:43.381+02:00  INFO 23176 --- [appointment-booking] [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint beneath base path '/actuator'
2025-10-14T14:16:43.446+02:00  INFO 23176 --- [appointment-booking] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http)
Health Endpoint

4.3. Running Unit Tests

Execute the default Spring Boot test to verify the application context loads correctly:

mvn test

This runs the AppointmentBookingApplicationTests class, which contains a single test method:

@SpringBootTest
class AppointmentBookingApplicationTests {

    @Test
    void contextLoads() {
    }
}

Understanding the Context Load Test

The contextLoads() test method appears empty but serves a crucial purpose:

  • Purpose: Verifies that the Spring application context can be successfully loaded and all beans can be created without errors

  • What it tests:

    • All @Configuration classes are valid

    • All @Component, @Service, @Repository beans can be instantiated

    • Dependency injection works correctly

    • No circular dependencies exist

    • Application properties are valid

  • Why it’s important: This test catches configuration errors early, before you deploy or run integration tests

The @SpringBootTest annotation:

  • Loads the complete Spring application context

  • Uses the same configuration as your running application

  • Provides a full integration test environment

Note

Think about it: Why might this simple test be more valuable than it appears? What types of issues would cause this test to fail even though the method body is empty?

4.4. Configuring Maven Test Plugins

To ensure proper test execution and reporting in CI/CD environments, add the following Maven plugins to your pom.xml in the <build><plugins> section:

<!-- Unit tests -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <includes>
            <include>**/*Test.java</include>
            <include>**/*Tests.java</include>
        </includes>
    </configuration>
</plugin>

<!-- Integration tests -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <configuration>
        <includes>
            <include>**/*IT.java</include>
        </includes>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>

<!-- Test reports (for CI pipeline) -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-report-plugin</artifactId>
    <version>3.5.4</version>
    <executions>
        <execution>
            <phase>verify</phase>
            <goals>
                <goal>report-only</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <aggregate>true</aggregate>
    </configuration>
</plugin>

Understanding Maven Test Lifecycle

Maven distinguishes between different types of tests:

  • Unit Tests (*Test.java, *Tests.java): Run by Surefire plugin during mvn test phase

  • Integration Tests (*IT.java): Run by Failsafe plugin during mvn verify phase

  • Test Reports: Generated for CI/CD pipeline consumption and team visibility

This configuration ensures:

  • Tests run correctly in both local development and CI environments

  • Proper separation between unit and integration tests

  • Standardized test reporting for automated pipelines

Note

Spring Boot’s parent POM manages some plugin versions automatically, so explicit version declarations for such plugins are unnecessary. This approach ensures compatibility and reduces maintenance overhead. For further details, refer to the official Spring Boot documentation on the versions managed by Spring Boot.

4.5. Exploring Actuator Endpoints

With your application running, explore these actuator endpoints:

Using Actuator for Monitoring

Actuator endpoints provide production-ready features:

  • Health checks: Monitor application and dependency status

  • Metrics: Track performance, memory usage, and custom metrics

  • Environment info: View configuration properties and system information

  • Application info: Display build information, Git commit details

Note

Think about it: How could you use these actuator endpoints in a production environment? What information would be most valuable for operations teams?

To maintain consistent code formatting across your project and team, consider adding the Spotless Maven plugin. This plugin automatically formats your code and ensures build failures when formatting standards aren’t met.

Benefits of Using Spotless

  • Consistent Code Style: Enforces uniform formatting across all team members

  • Automated Cleanup: Removes unused imports and applies standard formatting

  • Build Integration: Fails builds when code doesn’t meet formatting standards

  • IDE Independence: Works regardless of individual IDE settings

  • Reduced Code Review Overhead: Eliminates formatting discussions in pull requests

Configuration

Add the Spotless plugin to your pom.xml in the <build><plugins> section, alongside the existing Spring Boot Maven plugin:

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

        <!-- Add Spotless plugin here -->
        <plugin>
            <groupId>com.diffplug.spotless</groupId>
            <artifactId>spotless-maven-plugin</artifactId>
            <version>2.43.0</version> <!-- you can try to update to the newest version and then adjust configuration accordingly -->
            <configuration>
                <java>
                    <removeUnusedImports/>
                    <eclipse/>
                </java>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Why in the <build><plugins> section?

  • Maven plugins belong in the build configuration section

  • The <executions> block with <goal>check</goal> runs automatically during the verify phase

  • This ensures formatting validation occurs before packaging and deployment

Usage Commands

  • Check formatting: mvn spotless:check - Verifies code formatting without making changes

  • Apply formatting: mvn spotless:apply - Automatically formats all Java files

  • Build with formatting check: mvn clean verify - Includes formatting validation in the build process

Tip

Run mvn spotless:apply before committing code to ensure your changes pass the CI pipeline formatting checks.

5. Repository Setup and Collaboration

Congratulations! Your Spring Boot application is now ready for development.

Your trainer will provide access to the Student Repository for implementing solutions during the Java Backend Developer course.

5.1. What’s Already Provided in the Student Repository

When you clone the Student Repository, you’ll find several pre-configured files to help you get started:

1. README.md

The repository includes a comprehensive README.md file with:

  • Project Overview - Contains links to two additional repositories:

    • Instructions repository with detailed exercise descriptions

    • Reference implementation repository with complete solution examples

Student Repository README

2. CI/CD Pipeline Configuration (.github/workflows/ci.yml)

A pre-configured GitHub Actions workflow that provides automated build and test execution on pushes to solution/ branches and pull requests to main or solution/ branches.

Important

GitHub Actions Free Tier Limitation: The CI pipeline should be modified carefully (if at all) as GitHub Actions provides only 2,000 minutes per month for private repositories on the GitHub Free plan for organizations.

What this CI configuration means:

  • Triggers: Runs automatically when you push to any solution/** branch or create pull requests

  • Environment: Uses Ubuntu with JDK 21 and Maven dependency caching for faster builds

  • Build Process: Executes mvn clean verify to compile, test, and package your application

  • Test Reporting: Generates HTML test reports and uploads them as artifacts for 7 days

  • Always Runs: Test report generation occurs even if tests fail, helping with debugging

3. OpenAPI Specification (api/openapi.yml)

The repository includes a complete OpenAPI specification file.

This specification will be essential for the API development exercises in later training modules, where you’ll implement the endpoints according to this contract.

5.2. Getting Started

  1. Clone the repository to your local machine (e.g., C:\trainings\java-backend-developer-student)

  2. Copy all files from your Spring Boot application to the cloned repository

  3. Test the application in the new location

  4. Remove the original project files once verified

  5. Switch to your group’s working branch (e.g., working/group-1)

  6. Coordinate with your team to determine who will commit and push changes

  7. Create a pull request to your group’s solution branch (solution/group-X)

  8. Conduct code reviews and synchronize your team’s codebase

Note

Think about it: What are the benefits of working on a shared codebase versus individual repositories? How does this simulate real-world development practices?

6. Appendix

6.1. Maven and Alternatives

Maven is a popular build automation and dependency management tool for Java projects. It uses a declarative XML file (pom.xml) to manage project dependencies, build lifecycle, and plugins. Maven simplifies project setup, builds, testing, and deployment.

Alternatives to Maven include:

  • Gradle: Uses Groovy/Kotlin DSL, faster builds, flexible configuration.

  • Ant: Procedural build tool, less dependency management.

Official Documentation: https://maven.apache.org

6.2. 🆚 IntelliJ Run Config vs mvn spring-boot:run

This section compares two common ways to run Spring Boot applications during development.

Feature / Aspect IntelliJ Run Configuration mvn spring-boot:run

Startup Speed

✅ Faster (direct class execution, no Maven overhead)

❌ Slightly slower (starts Maven, resolves plugins/deps)

Build Process

Uses IntelliJ’s internal compiler

Uses Maven’s build lifecycle (compile, resources, etc.)

JAR Packaging

❌ Does not build JAR unless explicitly triggered

❌ Does not build JAR either, but can be configured to do so

Dependency Resolution

Uses IntelliJ’s project model

Uses Maven’s dependency resolution

Profile & Property Management

Requires manual setup in Run Config

✅ Easy via CLI flags (-Dspring-boot.run.profiles=dev)

Environment Independence

IDE-dependent

✅ Works anywhere Maven is installed

Plugin Features (e.g., layering)

❌ Not available

✅ Available via plugin configuration

Debugging Support

✅ Full IDE debugging support

❌ Limited unless run with debug flags

Hot Reload / DevTools

✅ Fully supported

✅ Supported

Consistency Across Team

❌ Depends on each developer’s IDE setup

✅ Consistent via shared pom.xml

CI/CD Compatibility

❌ Not suitable

✅ Ideal for automation and pipelines

Customization via pom.xml

❌ Not applicable

✅ Fully customizable

To summarize: use IntelliJ for fast local development and debugging, and mvn spring-boot:run for consistent, portable execution across environments.

6.3. Key Maven Dependency Configuration Tags

Below is a short overview of common <dependency> configuration tags you’ll encounter in a pom.xml, what they mean, when you’d typically use them, and links to further reading.

Tag What it does Typical use

<scope>

Defines when a dependency is included (e.g., compile, test, runtime, provided).

For example:

* compile – default; available everywhere

* provided – available at compile time; runtime provided by container

* test – only available during tests

* runtime – needed at runtime but not compile time

* system / import – special cases

<optional>

Marks a dependency as non-transitive: downstream projects that depend on your project will not automatically include it.

Use when you include a library internally but don’t want every user of your artifact to automatically bring it in (e.g., Lombok).

<exclusions>

Allows you to exclude specific transitive dependencies that would otherwise be brought in indirectly.

Use when a dependency brings in something you don’t want (e.g., conflicting version, large unused library, license issue).

For further reading:

6.4. About Spring

"Spring" can refer to the core Spring Framework itself or the entire collection of projects and modules that have been developed under its umbrella. With VMware and now its parent company, Broadcom, it has become a vast ecosystem of tools and libraries for building Java applications.

The Spring Boot and Spring Framework are free and open-source software released under the Apache 2.0 license.

Take a look at the official Spring website for more information: https://spring.io

Here are some additional Spring projects that you might find useful as you continue your development journey: