Spring Boot Project Setup | Java Backend Guide

Spring Boot Logging, Exception Handling, and Profiles - Complete Guide

Module 2: Java Spring Boot Fundamentals

What is Spring Boot?

Spring Boot is a Java-based framework built on top of Spring that simplifies the process of building production-ready backend services. It eliminates boilerplate configurations and allows developers to focus on application logic.

With embedded servers like Tomcat and built-in dependency management, Spring Boot projects can be launched with minimal setup.

Step 1: Generate Project Using Spring Initializr

Visit start.spring.io and configure your project:

  • Project: Maven
  • Language: Java
  • Spring Boot Version: 2.7.0 or higher (LTS preferred)
  • Group: com.example
  • Artifact: demo
  • Dependencies: Spring Web, Spring Boot DevTools, Lombok, Spring Data JPA, H2 (or MySQL)

Click “Generate” to download a `.zip` file of the project. Extract it to your workspace.

Spring Initializr is the official project generator for Spring Boot. Learn more at docs.spring.io.

Step 2: Understand Folder Structure

After extracting and opening the project in an IDE like IntelliJ IDEA or Eclipse, you’ll see this structure:

  • /src/main/java – your application’s Java source code
  • /src/main/resources – static files, `application.properties`, templates
  • /src/test/java – unit test files
  • pom.xml – the Maven build file containing dependency definitions

The main application class is usually found inside `com.example.demo` with the `@SpringBootApplication` annotation.

Step 3: Install & Configure Java + Maven

Ensure Java JDK 8 or 11 is installed:

java -version

Install Maven (if not already):

mvn -v

You can also configure the Java version and Maven home in your IDE settings.

Step 4: Build and Run the Project

In your terminal or IDE terminal:

mvn clean install

To run the application:

mvn spring-boot:run

Visit http://localhost:8080 to see if the server is running. By default, it will return a 404 until a controller is added.

Part 2: Spring Boot: Build Your First REST API

1. Create a Controller Class

In the src/main/java/com/example/demo directory, create a new Java class called HelloController.java:

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!";
    }
}
This class uses the @RestController annotation, which combines @Controller and @ResponseBody.

2. Run the App and Test the Endpoint

Now, start the Spring Boot application using your IDE or command line:

mvn spring-boot:run

Open your browser or Postman and go to:

http://localhost:8080/hello

You should see this response:

Hello, Spring Boot!

3. Using application.properties

Spring Boot uses a centralized config file: src/main/resources/application.properties.

Let’s add a custom message in the properties file:

app.welcome=Welcome to Spring Boot Config

Now modify your controller to read this value:

package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Value("${app.welcome}")
    private String welcomeMessage;

    @GetMapping("/welcome")
    public String getWelcomeMessage() {
        return welcomeMessage;
    }
}
Use @Value to inject values from the application.properties file.

4. Other Useful Properties

Here are some other common Spring Boot configuration settings:

# Change default port
server.port=9090

# Show SQL queries in logs
spring.jpa.show-sql=true

# Format SQL queries for readability
spring.jpa.properties.hibernate.format_sql=true

5. Add a Custom Base Path (Optional)

You can change the base path for all APIs:

server.servlet.context-path=/api/v1

Now the /hello endpoint becomes:

http://localhost:8080/api/v1/hello

Spring Boot Module 2 | Core API Concepts

Introduction to REST

REST stands for Representational State Transfer. It is a popular architectural style for designing APIs that communicate over HTTP. Spring Boot provides built-in support for creating REST APIs using annotations and classes.

A REST Controller is a Spring component that handles HTTP requests and sends JSON responses by default.

What is @RestController?

The @RestController annotation marks a Java class as a controller where every method returns a response body instead of a view.

@RestController = @Controller + @ResponseBody

This means you don’t need to write @ResponseBody on every method—Spring Boot handles JSON automatically.

Basic REST Controller Example

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 from REST Controller!";
    }
}

This class listens for GET requests at /hello and returns plain text. In a real app, you can return JSON or structured data.

Returning JSON Responses

You can return Java objects directly. Spring Boot converts them into JSON automatically:

public class User {
    private String name;
    private int age;

    // constructors, getters, setters
}
@GetMapping("/user")
public User getUser() {
    return new User("John Doe", 25);
}

The result will be:

{
  "name": "John Doe",
  "age": 25
}

HTTP Methods Used

  • @GetMapping – read data (GET request)
  • @PostMapping – create data (POST request)
  • @PutMapping – update data (PUT request)
  • @DeleteMapping – delete data (DELETE request)

These are part of Spring's Web MVC API annotations.

Benefits of Using REST Controllers

  • Fast API development: Built-in support for JSON and HTTP
  • Simple structure: One method per route
  • Scalable: Used in microservices, mobile backends, and web apps
  • Spring Boot friendly: No XML config or servlet setup needed

Module 2: application.properties vs application.yml in Spring Boot

Why Do Spring Boot Projects Need Config Files?

Every Spring Boot application needs a configuration file to define settings such as port numbers, database connections, logging behavior, profiles, and custom values.

These settings are usually placed in either application.properties or application.yml under the src/main/resources folder.

Both formats are supported by Spring Boot’s configuration system as described in the official Spring documentation.

What is application.properties?

The application.properties file uses a key-value pair structure where each line defines one setting.

# Example application.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=secret

It's simple, flat, and ideal for small or medium configurations.

What is application.yml?

The application.yml file uses YAML (YAML Ain’t Markup Language), which provides a hierarchical structure. It’s more readable for complex or nested configurations.

# Example application.yml
server:
  port: 8081

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testdb
    username: root
    password: secret
YAML is widely used in modern DevOps tools like Kubernetes, Docker Compose, and GitHub Actions.

Key Differences

  • Readability: YAML is cleaner for nested values; properties are simpler for flat configs.
  • Whitespace sensitivity: YAML is indentation-sensitive, while properties are not.
  • Verbosity: Properties require more typing for nested structures.
  • Error sensitivity: YAML is more prone to formatting mistakes due to indentation.

When to Use Each

Use application.properties if:

  • Your config is short and mostly flat
  • You prefer simple key-value notation
  • You want to reduce indentation errors

Use application.yml if:

  • Your config has nested blocks or complex structures
  • You are comfortable managing indentation
  • You use external YAML tools (CI/CD, Docker, Kubernetes)

Caution: Don’t Use Both

If both application.properties and application.yml exist in the same project, the behavior can be unpredictable depending on load order.

It’s best to use only one format for consistency.

Best Practices

  • Organize config by active profiles (e.g., application-dev.yml)
  • Store secrets securely using environment variables or Vault
  • Use @Value or @ConfigurationProperties to inject values into your code

Module 2: Logging, Exception Handling, and Profiles in Spring Boot

1. Logging in Spring Boot

Spring Boot uses SLF4J as its default logging API, and internally relies on Logback as the implementation.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger logger = LoggerFactory.getLogger(MyClass.class);

logger.info("App started successfully.");
logger.warn("This is a warning.");
logger.error("This is an error.");

By default, Spring Boot prints logs to the console, but you can configure file output in application.properties:

# application.properties
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.file.name=logs/myapp.log

2. Exception Handling in Spring Boot

There are three levels of exception handling:

  • Method-level: Try-catch blocks (not preferred for REST)
  • Controller-level: Use @ExceptionHandler
  • Global: Use @ControllerAdvice

Example: Global Exception Handler

import org.springframework.web.bind.annotation.*;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Learn more about @ControllerAdvice for global error management.

3. Profiles in Spring Boot

Spring profiles allow you to separate configuration for different environments like dev, test, and prod.

Setting Profiles in application.yml

# application.yml
spring:
  profiles:
    active: dev

application-dev.yml

server:
  port: 8081
app:
  message: "Running in DEV mode"

application-prod.yml

server:
  port: 8080
app:
  message: "Running in PROD mode"

Spring automatically loads the appropriate config based on the active profile.

4. Use @Profile Annotation

Annotate Java beans or service classes to load only when a specific profile is active.

@Service
@Profile("dev")
public class DevDatabaseSeeder {
    // runs only in dev profile
}

Best Practices Summary

  • Use consistent logging with SLF4J and define levels properly
  • Always handle exceptions using @ControllerAdvice globally
  • Use profiles to manage dev/staging/production separation
  • Keep secret values out of version control by using external profile-specific files

Conclusion

Configuring robust logging, building centralized exception handling mechanisms, and organizing your environment-specific code using Spring Boot profiles are essential for creating professional, production-ready Java applications. Whether you're debugging issues, managing different deployment stages, or controlling sensitive configurations, these tools help keep your code clean, secure, and maintainable.

By mastering these features, you can write scalable and resilient Spring Boot applications suitable for real-world enterprise deployments. As seen in this guide, Spring Boot makes it simple to switch between profiles like dev, test, and prod, log critical application events, and gracefully handle runtime errors.

Want to dive deeper? Continue with our next post, where we’ll guide you through building real-world CRUD APIs with Spring Data JPA and connecting your application to a relational database like MySQL.

Post a Comment

1 Comments

  1. Thanks for the book reference. Could you please help me deploy a Vertex AI project on a JBoss server.

    ReplyDelete