Spring Boot Framework in Java
A Detailed Guide
Introduction
to Spring Boot
Spring Boot is a powerful
framework built on top of the Spring Framework, designed to simplify the
development of Java-based applications. It removes the need for extensive
configurations and provides a production-ready environment with minimal
setup.
Spring Boot follows a convention-over-configuration
approach, which means it automatically configures common functionalities,
allowing developers to focus on writing business logic instead of worrying
about boilerplate code.
Key
Features of Spring Boot
1. Standalone
Applications:
o
No need for external application servers (like
Tomcat or Jetty).
o
Comes with an embedded web server.
2. Auto-Configuration:
o
Automatically configures Spring applications based
on dependencies.
3. Microservices
Support:
o
Provides built-in tools for developing microservices
architecture.
4. Spring
Boot Starter Dependencies:
o
Simplifies dependency management with
pre-configured starter packs.
5. Embedded
Servers:
o
Supports embedded Tomcat, Jetty, and Undertow
for running web applications.
6. Spring
Boot Actuator:
o
Provides production-ready monitoring and health
check endpoints.
7. Spring Boot
CLI (Command Line Interface):
o
Enables rapid development without manually writing
configuration files.
8. Security
and Authentication:
o
Supports Spring Security for authentication
and authorization.
9. Spring
Boot DevTools:
o
Provides automatic restart and live reload for
quick development.
Spring
Boot Architecture
Spring Boot follows the Spring
Framework architecture but simplifies it with pre-built configurations
and starter dependencies.
1. Spring
Core Container:
o
Provides dependency injection and bean management.
2. Spring
MVC:
o
Used for building RESTful web applications.
3. Spring
Data:
o
Simplifies database access (supports JPA,
Hibernate, MongoDB, etc.).
4. Spring
Security:
o
Handles authentication and authorization.
5. Spring
Boot Auto-Configuration:
o
Configures the application automatically based on
the dependencies.
How to
Create a Spring Boot Application
There are multiple ways to create
a Spring Boot application:
1. Using
Spring Boot Initializr (Recommended)
o
Go to Spring Boot Initializr.
o
Select project type (Maven/Gradle).
o
Choose dependencies (Spring Web, Spring Data JPA, MySQL Driver, Lombok ,Thymeleaf etc.).
o
Generate and download the project.
o
Import it into an IDE (Eclipse, IntelliJ IDEA, or
VS Code).
2. Using
Spring Boot CLI
o
Install Spring Boot CLI.
o
Run the command:
spring init --dependencies=web my-spring-boot-app
o
Navigate into the project and run:
mvn spring-boot:run
Spring
Boot Project Structure
When you create a Spring Boot
application, it follows this structure:
my-spring-boot-app
│── src/main/java/com/example/demo
│ ├── DemoApplication.java (Main class)
│ ├── controller/
│ │
├── HelloController.java
│ ├── service/
│ │
├── HelloService.java
│ ├── repository/
│ │
├── UserRepository.java
│── src/main/resources
│ ├── application.properties (Configuration file)
│── pom.xml (Dependencies)
Spring
Boot Application Example
Let's create a simple Spring
Boot REST API.
1. Create
the Main Application Class
package
com.example.demo; import
org.springframework.boot.SpringApplication; import
org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class
DemoApplication { public
static void main(String[] args) { SpringApplication.run(DemoApplication.class,
args); } } |
- @SpringBootApplication
enables auto-configuration, component scanning, and configuration.
2. Create
a REST Controller
- @RestController
marks this class as a REST API controller.
- @RequestMapping("/api")
sets the base URL for endpoints.
- @GetMapping("/hello")
maps the GET request to /api/hello.
package com.example.demo.controller; import
org.springframework.web.bind.annotation.GetMapping; import
org.springframework.web.bind.annotation.RequestMapping; import
org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class HelloController
{
@GetMapping("/hello") public
String sayHello() { return
"Hello, Spring Boot!"; } } |
3.
Configure the application.properties
In src/main/resources/application.properties,
add:
- This
changes the default server port to 8081.
server.port=8081 spring.application.name=SpringBootDemo |
4. Run
the Application
- Open
a terminal and navigate to the project folder.
- Run:
mvn spring-boot:run
- Open
a browser and go to:
http://localhost:8081/api/hello
Output:
Hello, Spring Boot!
Spring
Boot with Database (MySQL)
Spring Boot makes it easy to
connect to databases using Spring Data JPA.
1. Add
Dependencies (pom.xml)
<dependencies> <!--
Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--
Spring Boot JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
<!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies>
|
2. Configure Database in application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
|
3. Create
a JPA Entity (Model)
package com.example.demo.model;
@Entity
@Table(name
= "users")
public class
User {
@Id
@GeneratedValue(strategy =
GenerationType.IDENTITY)
private Long id;
private String email;
// Getters and Setters
}
4. Create
a Repository
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> {
}
5. Create
a REST API for Database Operations
package com.example.demo.controller;
import com.example.demo.model.User;
import
com.example.demo.repository.UserRepository;
import
org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class
UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping
public List<User> getUsers() {
return userRepository.findAll();
}
@PostMapping
public User createUser(@RequestBody User
user) {
return userRepository.save(user);
}
}
Spring
Boot Advantages
Conclusion
Spring Boot simplifies Java
development by reducing configuration and providing built-in features like auto-configuration,
embedded servers, and database integration. It is widely used for REST
APIs, microservices, enterprise applications, and cloud-based solutions.
to create a working RESTful API with Spring Boot, Spring Data JPA, and MySQL.
Project
Structure
my-spring-boot-app
│──
src/main/java/com/example/demo
│ ├── DemoApplication.java (Main class)
│ ├── model/
│ │
├── User.java
│ ├── repository/
│ │
├── UserRepository.java
│ ├── service/
│ │
├── UserService.java
│ ├── controller/
│ │
├── UserController.java
│──
src/main/resources
│ ├── application.properties (Configuration file)
│──
pom.xml (Dependencies)
1. Main
Application Class (DemoApplication.java)
package com.example.demo; import
org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static
void main(String[] args) { SpringApplication.run(DemoApplication.class,
args); } } |
- @SpringBootApplication
enables auto-configuration and component scanning.
- SpringApplication.run(DemoApplication.class,
args); starts the application.
2. User
Model (User.java)
- Defines
a User entity with id, name, and email.
- Uses
@Entity for JPA mapping.
- Uses
@Table(name = "users") to specify table name.
package com.example.demo.model; import jakarta.persistence.*; @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy
= GenerationType.IDENTITY) private Long
id; private
String name; private
String email; //
Constructors public User()
{} public
User(String name, String email) { this.name
= name; this.email
= email; } // Getters
and Setters public Long
getId() { return
id; } public void
setId(Long id) { this.id
= id; } public String
getName() { return
name; } public void
setName(String name) { this.name
= name; } public String
getEmail() { return
email; } public void
setEmail(String email) { this.email
= email; } } |
3. User
Repository (UserRepository.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> {
}
- JpaRepository<User,
Long> provides built-in methods like save(), findAll(), findById(), and
delete().
4. User
Service (UserService.java)
- Implements
business logic for User operations.
package com.example.demo.service; import
com.example.demo.model.User; import
com.example.demo.repository.UserRepository; import
org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserService { private final
UserRepository userRepository; public
UserService(UserRepository userRepository) { this.userRepository
= userRepository; } public
List<User> getAllUsers() { return
userRepository.findAll(); } public
Optional<User> getUserById(Long id) { return
userRepository.findById(id); } public User
saveUser(User user) { return
userRepository.save(user); } public void
deleteUser(Long id) { userRepository.deleteById(id); } }
|
5. User
Controller (UserController.java)
- Provides
RESTful endpoints for CRUD operations:
- GET
/users → Get all users.
- GET
/users/{id} → Get user by ID.
- POST
/users → Create a new user.
- DELETE
/users/{id} → Delete user by ID.
package com.example.demo.controller; import
com.example.demo.model.User; import
com.example.demo.service.UserService; import
org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/users") public class UserController { private final
UserService userService; public
UserController(UserService userService) { this.userService
= userService; } // Get all
users @GetMapping public
List<User> getAllUsers() { return
userService.getAllUsers(); } // Get user
by ID @GetMapping("/{id}") public
Optional<User> getUserById(@PathVariable Long id) { return
userService.getUserById(id); } // Create
user @PostMapping public User
createUser(@RequestBody User user) { return
userService.saveUser(user); } // Delete
user by ID @DeleteMapping("/{id}") public String
deleteUser(@PathVariable Long id) { userService.deleteUser(id); return
"User deleted successfully!"; } }
|
6.
Configuration (application.properties)
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server.port=8080
- Configures
MySQL database connection.
- Sets
Hibernate to auto-update the database schema.
7.
Dependencies (pom.xml)
- Includes
spring-boot-starter-web, spring-boot-starter-data-jpa, and
mysql-connector-java.
<dependencies> <!--
Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--
Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- MySQL
Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--
Spring Boot DevTools (for hot reload) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>
|
8.
Running the Application
Step 1:
Create MySQL Database
CREATE DATABASE mydb;
Step 2:
Run the Spring Boot Application
mvn spring-boot:run
Step 3:
Test API Endpoints
Use Postman or cURL
to test API endpoints:
Create a
User (POST)
POST http://localhost:8080/users
Content-Type:
application/json
{
"name": "John Doe",
"email":
"johndoe@example.com"
}
Get All
Users (GET)
GET http://localhost:8080/users
Get User
by ID (GET)
GET http://localhost:8080/users/1
Delete a
User (DELETE)
DELETE http://localhost:8080/users/1
Conclusion
- This
Spring Boot application includes RESTful API endpoints for user
management.
- Uses
Spring Boot, Spring Data JPA, and MySQL.
- Follows
a structured MVC approach with Controller, Service, and Repository layers.
full Spring Boot
application with a form input page (HTML with Thymeleaf) to insert
user data into a MySQL database.
Project
Structure
my-spring-boot-app
│──
src/main/java/com/example/demo
│ ├── DemoApplication.java (Main class)
│ ├── model/
│ │
├── User.java
│ ├── repository/
│ │
├── UserRepository.java
│ ├── service/
│ │
├── UserService.java
│ ├── controller/
│ │
├── UserController.java
│──
src/main/resources
│ ├── templates/
│ │
├── index.html (Form input page)
│ │
├── users.html (List users page)
│ ├── application.properties (Configuration file)
│──
pom.xml (Dependencies)
1. Main
Application Class (DemoApplication.java)
package com.example.demo; import
org.springframework.boot.SpringApplication; import
org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static
void main(String[] args) { SpringApplication.run(DemoApplication.class,
args); } }
|
2. User Model (User.java)
package com.example.demo.model; import jakarta.persistence.*; @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy
= GenerationType.IDENTITY) private Long
id; private
String name; private
String email; //
Constructors public User()
{} public
User(String name, String email) { this.name
= name; this.email
= email; } // Getters
and Setters public Long
getId() { return
id; } public void
setId(Long id) { this.id
= id; } public String
getName() { return
name; } public void
setName(String name) { this.name
= name; } public String
getEmail() { return
email; } public void
setEmail(String email) { this.email
= email; } }
|
3. User
Repository (UserRepository.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> { }
|
4. User
Service (UserService.java)
package com.example.demo.service; import com.example.demo.model.User; import
com.example.demo.repository.UserRepository; import
org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { private final
UserRepository userRepository; public UserService(UserRepository
userRepository) { this.userRepository
= userRepository; } public
List<User> getAllUsers() { return
userRepository.findAll(); } public void
saveUser(User user) { userRepository.save(user); } }
|
5. User
Controller (UserController.java)
package com.example.demo.controller; import
com.example.demo.model.User; import
com.example.demo.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import
org.springframework.web.bind.annotation.*; @Controller public class UserController { private
final UserService userService; public
UserController(UserService userService) { this.userService
= userService; } // Show the form
page @GetMapping("/") public String
showForm(Model model) { model.addAttribute("user",
new User()); return
"index"; } // Handle
form submission @PostMapping("/saveUser") public String
saveUser(@ModelAttribute User user) { userService.saveUser(user); return
"redirect:/users"; } // Display
all users @GetMapping("/users") public String
listUsers(Model model) { model.addAttribute("users",
userService.getAllUsers()); return
"users"; } }
|
6. HTML Form Page (index.html)
Located in
src/main/resources/templates/index.html
<!DOCTYPE html> <html
xmlns:th="http://www.thymeleaf.org"> <head> <title>User
Form</title> </head> <body> <h2>Enter
User Details</h2> <form
action="#" th:action="@{/saveUser}"
th:object="${user}" method="post"> <label>Name:</label> <input
type="text" th:field="*{name}" required> <br><br> <label>Email:</label> <input
type="email" th:field="*{email}" required> <br><br> <button
type="submit">Save User</button> </form> </body> </html>
|
7. User
List Page (users.html)
Located in
src/main/resources/templates/users.html
<!DOCTYPE html> <html
xmlns:th="http://www.thymeleaf.org"> <head> <title>Users
List</title> </head> <body> <h2>Users
List</h2> <table
border="1"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <tr
th:each="user : ${users}"> <td
th:text="${user.id}"></td> <td
th:text="${user.name}"></td> <td
th:text="${user.email}"></td> </tr> </tbody> </table> <br> <a
href="/">Add New User</a> </body> </html>
|
8. Configuration (application.properties)
Located in
src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html server.port=8080
|
9.
Dependencies (pom.xml)
<dependencies> <!--
Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--
Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- MySQL
Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--
Spring Boot Starter Thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>
|
10.
Running the Application
Step 1:
Create MySQL Database
CREATE DATABASE mydb;
Step 2:
Run the Application
mvn spring-boot:run
Step 3:
Access the Application
1. Open the form
page:
👉 http://localhost:8080/
2. Submit
user data, then view users:
👉 http://localhost:8080/users
Conclusion
✅ A Spring
Boot application with Thymeleaf form
✅ Stores data in a MySQL database
✅ Lists users on a separate page