seven yevale's blog : Getting Started with Spring Boot

seven yevale's blog

Spring Boot is one of the most popular frameworks in the Java ecosystem, designed to simplify the process of building production-ready, stand-alone applications. It is widely used for developing microservices and web applications due to its minimal configuration requirements, embedded servers, and ease of use. In this guide, we'll walk through the basics of Spring Boot, how to set up a simple application, and essential concepts to get you started. Java Classes in Pune



1. What is Spring Boot?

Spring Boot is built on top of the Spring Framework and provides a streamlined development experience by reducing the amount of boilerplate code and configuration. It allows developers to create stand-alone applications that can be run directly using Java's main method without requiring an external web server.

Key Features of Spring Boot:

  • Auto-Configuration: Automatically configures Spring and third-party libraries based on the dependencies in your project.
  • Embedded Server: Ships with an embedded web server (e.g., Tomcat, Jetty) so you don’t need to install and configure an external server.
  • Production-Ready: Provides built-in features for monitoring, health checks, and metrics using Spring Boot Actuator.
  • Convention Over Configuration: Defaults to sensible settings, but allows customization as needed.

2. Setting Up Your Spring Boot Environment

Step 1: Install Java

Make sure you have Java Development Kit (JDK) installed on your system. Spring Boot requires JDK 8 or higher. You can check your Java version by running:

bash
java -version

Step 2: Set Up a Build Tool

Spring Boot supports both Maven and Gradle for managing dependencies and building your project.

  • Maven:
    • If using Maven, ensure you have mvn installed on your system.
  • Gradle:
    • If you prefer Gradle, you should have gradle installed.

Step 3: Create a New Spring Boot Project

The easiest way to start a Spring Boot project is by using Spring Initializr, a web-based tool provided by Spring. It helps you generate a project structure with the necessary dependencies.

  • Option 1: Using Spring Initializr Website

    • Visit Spring Initializr.
    • Choose your build system (Maven or Gradle).
    • Select the latest Spring Boot version.
    • Fill in the project details like Group, Artifact, Name, and Package.
    • Add the necessary dependencies (e.g., Spring Web, Spring Data JPA, etc.).
    • Download the project as a .zip file and extract it to your desired location.
  • Option 2: Using IntelliJ IDEA or Eclipse

    • Both IntelliJ IDEA and Eclipse support creating Spring Boot projects directly from their interfaces using Spring Initializr.

3. Understanding the Project Structure

Once you generate your project, you’ll find a basic project structure like this:

css
srcmain │ └─── java │ └─── com.example.demo │ └─── DemoApplication.java │ └─── resources │ └─── application.properties
  • DemoApplication.java: This is the entry point of your Spring Boot application. It contains the main method and is annotated with @SpringBootApplication.
  • application.properties (or application.yml): This file is used for externalizing configuration. You can define various properties like database connection settings, server port, etc. 

    Java Course in Pune



4. Building a Simple Spring Boot Application

Let’s build a simple "Hello World" REST API using Spring Boot.

Step 1: Add Spring Web Dependency

Ensure that the Spring Web dependency is included in your pom.xml (Maven) or build.gradle (Gradle) file. This dependency is necessary for building web applications and REST APIs.

  • Maven (pom.xml):

    xml
    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  • Gradle (build.gradle):

    gradle
    implementation 'org.springframework.boot:spring-boot-starter-web'

Step 2: Create a REST Controller

In the src/main/java directory, create a new package (e.g., com.example.demo.controller) and add a REST controller to handle HTTP requests.

java
package com.example.demo.controller; 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, World!"; } }
  • @RestController: Tells Spring that this class is a REST controller, capable of handling HTTP requests.
  • @GetMapping("/hello"): Maps HTTP GET requests to the /hello URL path to the sayHello() method.

Step 3: Run the Application

  • Open the DemoApplication.java file, which contains the main method.
  • Right-click the file and choose Run (or use your IDE’s run command).
  • The Spring Boot application will start, and an embedded Tomcat server will be running on port 8080 by default.

You can now visit http://localhost:8080/hello in your browser, and you should see the response:

Hello, World!

5. Customizing Configuration

Spring Boot applications can be easily configured using the application.properties or application.yml file located in the src/main/resources directory. Here are some common configurations:

Changing the Server Port:

To run the server on a different port, you can add the following line to application.properties:

properties
server.port=9090

This will start the application on port 9090 instead of the default port 8080.

Setting Log Level:

You can control the logging level for your application:

properties
logging.level.org.springframework=INFO logging.level.com.example=DEBUG

6. Adding Database Support

Spring Boot makes it easy to connect to databases using the Spring Data JPA library.

Step 1: Add Database Dependency

To connect to a relational database, add the following dependency for Spring Data JPA and the required database driver:

  • Maven (pom.xml):

    xml
    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
  • Gradle (build.gradle):

    gradle
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa' runtimeOnly 'com.h2database:h2'

Step 2: Configure Database Settings

In application.properties, you can configure the database connection:

properties
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.hibernate.ddl-auto=update

Step 3: Create an Entity and Repository

Create an Entity that represents a table in your database and a Repository for data access.

java
package com.example.demo.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class User { @Id private Long id; private String name; // Getters and Setters }
java
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> { }

Now, Spring Boot will handle database interactions with minimal configuration! Java Training in Pune



7. Next Steps: Adding More Functionality

After getting familiar with basic concepts, you can explore more advanced Spring Boot features:

  • Spring Security: Add authentication and authorization to your app.
  • Spring Boot Actuator: Monitor your application with built-in health checks and metrics.
  • Spring Cloud: Build cloud-native microservices with support for distributed systems, service discovery, and load balancing.
In:
  • Career
On: 2024-09-23 07:33:08.034 http://jobhop.co.uk/blog/syevale111/getting-started-with-spring-boot