SpringBoot_notes_for_interview
SpringBoot_notes_for_interview
properties
Copy code
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=rootpassword
logging.level.org.springframework=INFO
6. Spring Boot Actuator:
○ Spring Boot Actuator provides a set of production-ready features,
such as health checks, metrics, and monitoring, which can be easily added to your
Spring Boot application.
○ It exposes built-in endpoints like /health, /metrics, /info, etc.,
which provide information about the application's status, performance, and
configuration.
7. Spring Boot DevTools:
○ DevTools is a set of tools that helps improve the developer
experience by providing features such as automatic restarts, live reload, and
enhanced debugging support.
○ It is often used during development to speed up the development
process.
8. Spring Boot CLI (Command Line Interface):
○ Spring Boot CLI is a command-line tool that allows developers to run
Spring Boot applications from the command line using Groovy scripts. It’s often
used for quick prototyping and development.
sql
Copy code
+-------------------------------------------+
| Spring Boot Application |
| (Entry Point with main() method) |
+-------------------------------------------+
|
v
+-------------------------------------------+
| Spring Boot Auto Configuration |
| (Configures beans automatically) |
+-------------------------------------------+
|
v
+-------------------------------------------+
| Embedded Web Server (Tomcat, etc.) |
| (Handles HTTP requests) |
+-------------------------------------------+
|
v
+-------------------------------------------+
| Spring Boot Starters (e.g., Web, |
| Data JPA, Security, etc.) |
+-------------------------------------------+
|
v
+-------------------------------------------+
| Spring Boot Configuration |
| (application.properties / YAML) |
+-------------------------------------------+
|
v
+-------------------------------------------+
| Spring Boot Actuator (Metrics, |
| Health Checks, Monitoring, etc.) |
+-------------------------------------------+
|
v
+-------------------------------------------+
| Spring Boot DevTools (Development |
| Tools: Auto-restart, Live Reload) |
+-------------------------------------------+
Summary of Spring Boot Architecture
• Simplified Configuration: Spring Boot reduces the need for complex
configurations by using auto-configuration and sensible defaults.
• Embedded Servers: Spring Boot allows you to run web applications with
embedded servers, eliminating the need for external servers like Tomcat.
• Starters: Predefined starter templates make it easier to add functionality
(e.g., web support, database access) to your application.
• Production-Ready: Built-in features like health checks, metrics, and
monitoring make it easy to deploy and manage your application in production.
• Microservices: Spring Boot is a popular choice for building microservices
because of its minimal configuration and ease of deployment.
Spring Boot simplifies the development of Spring applications, making it easier to
get started and be productive with minimal configuration. Whether you're building a
monolithic application or a microservice, Spring Boot's architecture provides the
necessary tools to help you succeed.
java
Copy code
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.getUserById(id);
return ResponseEntity.ok(user);
}
}
2. Business Layer (Service Layer)
• Responsibilities: The business layer contains the core business logic and
validations. It acts as an intermediary between the presentation and persistence
layers. It should not directly deal with database operations but instead focus on
business rules, validation, and transactions.
• Components:
○ Service Layer: In Spring Boot, the service layer is typically a
@Service annotated class. It holds the business logic and validation for the
application.
○ Validation: This layer is responsible for ensuring that the input
data is correct and meets business requirements. Validation can be done using Java
validation annotations (@NotNull, @Size, etc.) or custom validation logic.
○ Authorization: Some authorization logic may be placed here, although
a lot of it is often handled by the presentation layer (e.g., via Spring Security).
• Key Annotations:
○ @Service: Used to define a service class, where business logic
resides.
○ @Transactional: Ensures that methods in the service layer are
executed within a transactional context, providing rollback capabilities in case of
failure.
Example:
java
Copy code
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
return userRepository.findById(id).orElseThrow(() -> new
ResourceNotFoundException("User not found"));
}
public User createUser(User user) {
// Business validation logic
return userRepository.save(user);
}
}
3. Persistence Layer (Data Access Layer)
• Responsibilities: The persistence layer is responsible for data access and
storage logic. This layer communicates with the database and ensures that data is
saved, retrieved, updated, or deleted. It abstracts away the details of data
storage and management from the rest of the application.
• Components:
○ Repositories: The persistence layer is often represented by the
repository pattern in Spring Boot. Spring Data JPA (or other Spring Data projects)
allows you to define repositories that interact with the database. The @Repository
annotation is used here to mark classes responsible for database operations.
○ Entities: These are Java objects (POJOs) that represent the tables in
the database. They are annotated with @Entity and often include mapping annotations
like @Id, @Column, etc.
• Key Annotations:
○ @Repository: Marks the class as a Spring Data repository, allowing it
to interact with the database.
○ @Entity: Marks a class as a JPA entity, which is mapped to a database
table.
○ @Id: Marks the primary key of the entity.
○ @Query: Allows custom SQL queries to be defined in repositories.
Example:
java
Copy code
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
// Getters and setters
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}
4. Database Layer (Actual Database)
• Responsibilities: This layer represents the actual database where data is
stored. It could be any relational (e.g., MySQL, PostgreSQL) or NoSQL database
(e.g., MongoDB, Cassandra).
• Components:
○ Database Management System (DBMS): The DBMS handles the storage,
retrieval, and manipulation of data. Spring Boot can easily integrate with most
popular DBMS systems through JDBC or JPA.
○ Database Tables & Relationships: These are the actual tables and
relationships in the database that store data. Entities in the application
correspond to these tables.
• Key Aspects:
○ Spring Boot allows you to configure the database using the
application.properties or application.yml files for settings like the database URL,
username, password, and other connection details.
○ Spring Data JPA makes database interaction easier by abstracting much
of the underlying complexity of database operations (such as CRUD operations) and
providing automatic query generation.
Example (Database Configuration in application.properties):
properties
Copy code
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
sql
Copy code
+--------------------------------------------------+
| Presentation Layer (Web Layer) |
| (Handles HTTP requests, JSON conversion, etc.) |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| Business Layer (Service Layer) |
| (Business Logic, Validation, Authorization) |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| Persistence Layer (Data Access Layer) |
| (Repository, JPA, DAO, etc.) |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| Database Layer (DB) |
| (Database such as MySQL, PostgreSQL, etc.) |
+--------------------------------------------------+