0% found this document useful (0 votes)
45 views65 pages

Spring Boot

JDBC is used in Spring Boot for direct database interaction, offering lightweight and flexible operations suitable for performance-critical applications. It allows for custom SQL queries and integrates seamlessly with legacy systems, enhanced by features like JdbcTemplate and DataSource management. Additionally, Spring Boot provides various annotations to simplify application configuration and management, including core annotations, dependency injection, and transaction management.

Uploaded by

ankit thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views65 pages

Spring Boot

JDBC is used in Spring Boot for direct database interaction, offering lightweight and flexible operations suitable for performance-critical applications. It allows for custom SQL queries and integrates seamlessly with legacy systems, enhanced by features like JdbcTemplate and DataSource management. Additionally, Spring Boot provides various annotations to simplify application configuration and management, including core annotations, dependency injection, and transaction management.

Uploaded by

ankit thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Notes

Q why jdbc is used in spring boot

In Spring Boot, JDBC (Java Database Connectivity) is used as a fundamental API for
interacting with relational databases. While Spring Boot provides higher-level abstractions like
JPA (Java Persistence API) and Spring Data, JDBC is often used for direct and fine-grained
database operations. Here's why JDBC is used in Spring Boot:

1. Direct Database Interaction

●​ JDBC allows you to execute SQL queries directly, making it suitable for applications
where you need precise control over database interactions.

2. Lightweight and Flexible

●​ For simple use cases or performance-critical applications, using JDBC directly can be
more lightweight than abstracting operations through JPA or ORM frameworks.

3. Custom SQL Queries

●​ JDBC is ideal when the application requires complex or custom SQL queries that may
not be easily implemented with higher-level abstractions.

4. Compatibility with Legacy Systems

●​ If you’re working with legacy systems that already use raw SQL queries, JDBC provides
a seamless way to integrate with those databases.

5. Transaction Management

●​ Spring Boot integrates JDBC with Spring’s transaction management, allowing you to use
programmatic or declarative transactions for database operations.

6. Integration with Spring Boot Features

●​ JDBC in Spring Boot is enhanced by features like:


○​ JdbcTemplate: Simplifies interaction with the database by reducing boilerplate
code for executing queries, handling exceptions, and managing resources.
○​ DataSource Management: Spring Boot auto-configures a DataSource for your
application, making it easier to establish a database connection.

Example Use Case:

Here’s a simple example using JdbcTemplate in Spring Boot:

java
Copy code
@Service
public class UserService {

@Autowired
private JdbcTemplate jdbcTemplate;

public List<User> getAllUsers() {


String sql = "SELECT * FROM users";
return jdbcTemplate.query(sql, (rs, rowNum) ->
new User(
rs.getInt("id"),
rs.getString("name"),
rs.getString("email")
));
}
}

When to Use JDBC in Spring Boot:

●​ When you need fine-grained control over SQL.


●​ For simple applications or microservices where ORM frameworks may be overkill.
●​ When performance is critical and the overhead of an ORM is unnecessary.
●​ For batch processing and direct execution of SQL scripts.

By combining JDBC with Spring Boot’s capabilities, you can achieve both simplicity and
powerful database interaction.

==============================

Mostly used annotations in spring boot


Spring Boot relies on annotations to reduce boilerplate code and configure applications
efficiently. Below is a detailed explanation of the most commonly used annotations in Spring
Boot, categorized based on their purpose.

1. Core Annotations
@SpringBootApplication

●​ Marks the main class of a Spring Boot application.


●​ Combines three annotations:
○​ @Configuration: Marks the class as a source of bean definitions.
○​ @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration
feature.
○​ @ComponentScan: Scans the package for Spring components.

Example:​
javak​
Copy code​
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

2. Dependency Injection and Bean Management


@Component

●​ Marks a class as a Spring-managed component (bean).


●​ Scanned during component scanning.

Example:​
java​
Copy code​
@Component
public class MyService {
public void performTask() {
System.out.println("Task performed.");
}
}

●​

@Service

●​ A specialization of @Component for service-layer classes.


●​ Indicates that the class contains business logic.

Example:​
java​
Copy code​
@Service
public class UserService {
public String getUser() {
return "John Doe";
}
}

●​

@Repository

●​ A specialization of @Component for the persistence layer.


●​ Used to indicate a class that interacts with the database.

Example:​
java​
Copy code​
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

@Controller

●​ Marks a class as a Spring MVC controller for handling web requests.

Example:​
java​
Copy code​
@Controller
public class HomeController {
@RequestMapping("/")
public String home() {
return "index";
}
}

●​

@RestController

●​ Combines @Controller and @ResponseBody.


●​ Indicates that the class handles REST API requests, and the response is serialized to
JSON or XML.

Example:​
java​
Copy code​
@RestController
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob", "Charlie");​ ​
}
}

3. Configuration and Initialization


@Configuration

●​ Marks a class as a source of bean definitions.

Example:​
java​
Copy code​
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}

●​

@Bean

●​ Indicates that a method produces a bean managed by the Spring container.

Example:​
java​
Copy code​
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}

🔄 1. Full Bean Life Cycle Flow (High-Level)


1.​ Object Instantiation (using new)​

2.​ Populate properties (DI – dependencies injected)​

3.​ BeanNameAware (bean gets its name)​

4.​ BeanFactoryAware / ApplicationContextAware (gives access to container)​

5.​ Pre-initialization logic (BeanPostProcessor)​

6.​ Custom init method (@PostConstruct or afterPropertiesSet())​

7.​ Ready to use​

8.​ Custom destroy method (@PreDestroy or destroy())

@Value

●​ Injects values into fields or methods from application properties.

Example:​
java​
Copy code​
@Value("${app.name}")
private String appName;

●​

@PropertySource

●​ Loads properties from an external .properties or .yml file.

Example:​
java​
Copy code​
@Configuration
@PropertySource("classpath:application.properties")
public class PropertyConfig {
}

4. Spring MVC Annotations


@RequestMapping

●​ Maps HTTP requests to handler methods.


●​ Can be applied at the class and method levels.

Example:​
java​
Copy code​
@RestController
@RequestMapping("/api")
public class ApiController {
@RequestMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob");
}
}

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping

●​ Specialized versions of @RequestMapping for specific HTTP methods.

Example:​
java​
Copy code​
@RestController
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob");
}
}
●​

@PathVariable

●​ Binds a method parameter to a URI template variable.

Example:​
java​
Copy code​
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {
return "User ID: " + id;
}

●​

@RequestParam

●​ Binds a method parameter to a query string parameter.

Example:​
java​
Copy code​
@GetMapping("/search")
public String search(@RequestParam String query) {
return "Search Query: " + query;
}

5. Data Access
@Entity

●​ Marks a class as a JPA entity (maps to a database table).

Example:​
java​
Copy code​
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


}

●​

@Table
●​ Specifies the table name for an entity.

Example:​
java​
Copy code​
@Entity
@Table(name = "users")
public class User {
}

●​

@Id

●​ Specifies the primary key of an entity.

Example:​
java​
Copy code​
@Id
private Long id;

●​

@GeneratedValue

●​ Specifies the generation strategy for primary keys.

Example:​
java​
Copy code​
@GeneratedValue(strategy = GenerationType.IDENTITY)

●​

6. Transaction Management

@Transactional
●​ Marks a method or class as transactional (rollbacks in case of exceptions).

Example:​
java​
Copy code​
@Service
public class UserService {

@Transactional
public void updateUser(User user) {
// Database operations
}
}

✅ Why use @Transactional in the Service Layer?


●​ The Service layer is responsible for the business logic and coordinates transactions
involving multiple operations (like saving multiple entities, updating and saving, etc.).​

●​ Placing @Transactional here ensures atomicity — all operations within the method
either succeed together or fail together (rolled back).​

✅ Example:
java
CopyEdit
@Service
public class StudentServiceImpl implements StudentService {

@Autowired
private StudentRepository repository;

@Override
@Transactional
public Student updateStudent(Long id, Student student) {
Student existing = repository.findById(id).orElseThrow();
existing.setName(student.getName());
existing.setEmail(student.getEmail());
return repository.save(existing);
}
}

❌ Don't use @Transactional in:


Layer Why Not?

Controller It's just an entry point, should not manage transactions.

Repository Spring Data JPA repositories already use transactions


internally.

⚙️ Common Properties of @Transactional


Property Default Description

propagation REQUIRED Defines how transactions should


propagate

isolation DEFAULT Defines the isolation level of the


transaction

rollbackFor none Specifies exceptions that trigger


rollback

readOnly false Marks the transaction as read-only

timeout -1 Sets the timeout in seconds

🔁 Propagation Types
Type Description

REQUIRED Join existing or create new (default)

REQUIRES_NEW Always create a new transaction

MANDATORY Must be in existing transaction or throws


exception

NEVER Must NOT be in a transaction

SUPPORTS Runs in a transaction if one exists

NOT_SUPPORTED Runs outside of any transaction

NESTED Creates a nested transaction

🔸 Example:
java

CopyEdit

@Transactional(propagation = Propagation.REQUIRES_NEW)

🔐 Isolation Levels
Level Description

READ_UNCOMMITTED Dirty reads allowed

READ_COMMITTED Prevents dirty reads

REPEATABLE_READ Prevents dirty and non-repeatable reads

SERIALIZABLE Full isolation (slowest but safest)

🔸 Example:
java

CopyEdit

@Transactional(isolation = Isolation.SERIALIZABLE)

🔄 Rollback Conditions
By default, Spring rolls back on unchecked exceptions (RuntimeException, Error) only.

🔸 To rollback on a checked exception:


java

CopyEdit

@Transactional(rollbackFor = Exception.class)
7. Exception Handling
@ControllerAdvice

●​ A global exception handler for Spring MVC controllers.

Example:​
java​
Copy code​
@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String>
handleRuntimeException(RuntimeException ex) {
return new ResponseEntity<>("Error: " + ex.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}

●​

8. Scheduling

@Scheduled

●​ Marks a method to run at fixed intervals or cron schedules.

Example:​
java​
Copy code​
@Service
public class ScheduledTask {

@Scheduled(fixedRate = 5000)
public void runTask() {
System.out.println("Task executed!");
}
}

These annotations simplify Spring Boot development, making the framework highly configurable
and easy to use.

🔹 1. @Qualifier – Resolve Ambiguity


When multiple beans of the same type are available, Spring can't decide which one to inject.​
Use @Qualifier to specify exactly which bean to use.

✅ Example:
java

CopyEdit

@Component

public class Dog implements Animal {

public void speak() {

System.out.println("Dog barks");

@Component

public class Cat implements Animal {

public void speak() {

System.out.println("Cat meows");

@Component

public class Zoo {

private final Animal animal;

@Autowired

public Zoo(@Qualifier("cat") Animal animal) {

this.animal = animal;
}

public void makeSound() {

animal.speak(); // Output: Cat meows

🔹 2. @Primary – Default Bean for Autowiring


When there are multiple beans of the same type, and no @Qualifier is used, Spring injects
the one marked with @Primary.

✅ Example:
java

CopyEdit

@Component

@Primary

public class Dog implements Animal {

public void speak() {

System.out.println("Dog barks");

@Component

public class Cat implements Animal {

public void speak() {

System.out.println("Cat meows");

}
}

@Component

public class Zoo {

@Autowired

private Animal animal;

public void makeSound() {

animal.speak(); // Output: Dog barks

🔹 3. @Scope – Bean Lifecycle Control


Defines the scope of a Spring bean. Common scopes:

●​ singleton (default): One instance per Spring container.​

●​ prototype: New instance each time it's requested.​

●​ request, session (web applications only)​

✅ Example:
java

CopyEdit

@Component

@Scope("prototype")

public class UserService {

public UserService() {
System.out.println("New UserService instance created");

In this case, each injection or context call to UserService will create a new object.

🌱 Lifecycle of a Bean in Spring Framework


In Spring, the Bean Lifecycle defines the steps a bean goes through from creation to
destruction in the Spring container. Here's a detailed yet concise breakdown:

🔄 Bean Lifecycle Phases


1. Instantiation

●​ Spring creates the bean instance using Java reflection or constructor injection.​

java

CopyEdit

MyBean bean = new MyBean();

2. Populate Properties

●​ Spring injects dependencies (like via @Autowired, constructor/setters, or XML).​

java

CopyEdit

bean.setSomeDependency(dep);

3. Set Bean Name


●​ If the bean implements BeanNameAware, Spring calls:​

java

CopyEdit

setBeanName(String name);

4. Set Bean Factory

●​ If the bean implements BeanFactoryAware, Spring injects BeanFactory:​

java

CopyEdit

setBeanFactory(BeanFactory factory);

5. Set ApplicationContext

●​ If the bean implements ApplicationContextAware, Spring injects


ApplicationContext.​

java

CopyEdit

setApplicationContext(ApplicationContext ctx);

6. Pre-initialization (BeanPostProcessor – before init)

●​ Any custom logic defined in a BeanPostProcessor (e.g., logging, modifying bean):​

java

CopyEdit

postProcessBeforeInitialization(bean, beanName);
7. Initializing Bean

●​ Bean performs custom init logic:​

If bean implements InitializingBean:​



java​
CopyEdit​
afterPropertiesSet();

○​
○​ Or if init-method is defined in XML or @PostConstruct is used.​

8. Post-initialization (BeanPostProcessor – after init)

●​ Final custom modifications before the bean is ready for use:​

java

CopyEdit

postProcessAfterInitialization(bean, beanName);

9. Ready to Use

●​ Bean is now fully initialized and can be used in the application.​

10. Destruction

●​ When the container is closed:​

If the bean implements DisposableBean:​



java​
CopyEdit​
destroy();
○​
○​ Or if destroy-method is defined in XML or @PreDestroy is used.​

✅ Diagram (Text Format)


csharp

CopyEdit

[Instantiation]

[Populate Properties]

[setBeanName() → setBeanFactory() → setApplicationContext()]

[BeanPostProcessor (before init)]

[Custom init (afterPropertiesSet() / @PostConstruct)]

[BeanPostProcessor (after init)]

[Ready to use]

[Container shutdown]

[destroy() / @PreDestroy]
======================

Topics :-
●​ Spring boot Archetucture -
https://www.geeksforgeeks.org/spring-boot-architecture/?ref=lbp​

●​ Important Methods of HTTP


https://www.geeksforgeeks.org/spring-boot-introduction-to-restful-web-services/?ref=lbp​

●​
Diff
spring framework vs spring MVC vs spring boot

1. Spring Framework

The Spring Framework is a comprehensive framework for enterprise Java applications. It


provides tools for dependency injection, aspect-oriented programming, data access, transaction
management, and more.

Key Features:

●​ Dependency Injection (DI): Manages object creation and their dependencies using
inversion of control (IoC).
●​ Aspect-Oriented Programming (AOP): Allows separation of cross-cutting concerns like
logging or security.
●​ Transaction Management: Handles transactions declaratively without boilerplate code.
●​ Integration: Provides integration with various frameworks like Hibernate, JPA, and JMS.

Example:

Dependency Injection using Spring Framework

java
Copy code
@Component
public class Service {
public void serve() {
System.out.println("Service is serving...");
}
}

@Component
public class Client {
private final Service service;

@Autowired
public Client(Service service) {
this.service = service;
}

public void performTask() {


service.serve();
}
}

// Main Configuration
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {}
// Main Application
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
Client client = context.getBean(Client.class);
client.performTask();
}
}

2. Spring MVC

Spring MVC is a module of the Spring Framework that provides a framework for building web
applications. It follows the Model-View-Controller (MVC) design pattern.

Key Features:

●​ DispatcherServlet: The front controller that handles all HTTP requests and responses.
●​ Model: Represents application data.
●​ View: Defines the presentation layer (e.g., JSP, Thymeleaf).
●​ Controller: Processes user requests and interacts with the model.

Example:

Spring MVC Web Application

java
Copy code
@Controller
public class GreetingController {

@GetMapping("/greet")
public String greet(Model model) {
model.addAttribute("message", "Hello, Spring MVC!");
return "greeting"; // Points to `greeting.jsp` in
`/WEB-INF/views`
}
}

// Configuration
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.example")
public class WebConfig extends WebMvcConfigurerAdapter {}

// greeting.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<h1>${message}</h1>
</body>
</html>

3. Spring Boot

Spring Boot simplifies the development of Spring-based applications by removing boilerplate


code and configurations. It is built on top of the Spring Framework and provides out-of-the-box
defaults, reducing manual setup.

Key Features:

●​ Auto-Configuration: Automatically configures Spring components based on classpath


entries.
●​ Embedded Servers: Comes with an embedded Tomcat/Jetty/Undertow server for
running applications.
●​ Starter Dependencies: Pre-configured dependencies for common tasks (e.g.,
spring-boot-starter-web).
●​ Production-Ready Features: Includes monitoring, health checks, and metrics with
Spring Actuator.

Example:

Spring Boot Web Application

java
Copy code
// Main Application
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}

// REST Controller
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}

// Application.properties (Optional)
server.port=8081
Run the application, and you can access it at http://localhost:8081/hello.

Comparison Table
Feature Spring Framework Spring MVC Spring Boot

Purpose Core enterprise Web application Simplified Spring


framework framework setup

Complexity High (manual Medium Low


configuration) (auto-configuration)

Setup Requires Requires Minimal setup


XML/JavaConfig DispatcherServlet required

Web Support Needs integration Provides MVC Simplifies web app


architecture setup

Server External server required External server Embedded server


required support

Example Use Dependency Injection, Building web apps Microservices, APIs


Case AOP

How They Work Together

●​ Spring Framework is the base that provides core features like DI, AOP, etc.
●​ Spring MVC builds on top of the Spring Framework for web applications.
●​ Spring Boot uses both Spring Framework and Spring MVC but removes the need for
extensive configuration.

This modularity allows developers to choose components based on their requirements. For
instance, you can use Spring Boot to quickly create a web application with Spring MVC,
leveraging the Spring Framework's core capabilities.

—---------

When to Use Each:

●​ Spring Framework: When you need fine-grained control over every aspect of your
application and want to leverage its extensive ecosystem.
●​ Spring MVC: When you're building a web application and need to handle HTTP
requests and responses.
●​ Spring Boot: When you want to rapidly develop and deploy Spring-based applications
with minimal configuration.

—----------------------
●​ Spring frame work
-​ Main feature is dependency injection
-​

●​ Spring boot
-​ Main feature is auto configuration

—-----------
Spring vs spring boot - Spring vs Spring Boot | Comparison | Ashok IT
—---------
========================

jpa vs hibernate vs orm vs jdbc in spring boot when to use which


one ?
When working with databases in Spring Boot, you may encounter terms like JPA, Hibernate,
ORM, and JDBC. Each has its purpose, and knowing when to use them depends on your
application's needs.

1. JPA (Java Persistence API)

JPA is a specification (not a framework) for managing relational data in Java applications. It
defines a standard for Object-Relational Mapping (ORM), allowing Java objects to be mapped to
database tables.

Key Features:

●​ Entity Management: Maps Java classes (entities) to database tables.


●​ Query Language: Provides JPQL (Java Persistence Query Language), which is
database-independent.
●​ Annotations: Simplifies database interaction with annotations like @Entity, @Table,
@Id.

Example:
java
Copy code
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


private String email;

// Getters and Setters


}

When using JPA, you also need an implementation like Hibernate.

2. Hibernate

Hibernate is an ORM framework and the most popular implementation of JPA. It simplifies
database interactions by automating the mapping between Java objects and database tables.

Key Features:

●​ Implements JPA specifications.


●​ Provides additional features like caching and lazy loading.
●​ Supports advanced queries with HQL (Hibernate Query Language).
Example:
java
Copy code
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}

In Spring Boot, you often use Hibernate behind the scenes when working with JPA.

3. ORM (Object-Relational Mapping)

ORM is a concept (not a library or framework) that describes the process of mapping Java
objects to database tables. JPA and Hibernate are implementations of the ORM concept.

Key Benefits of ORM:

●​ Eliminates boilerplate SQL code.


●​ Simplifies CRUD operations.
●​ Provides database independence.

Example:

Using Hibernate or JPA, you write minimal SQL while performing database operations:

java
Copy code
User user = new User();
user.setName("John");
userRepository.save(user); // ORM handles SQL generation and execution

4. JDBC (Java Database Connectivity)

JDBC is a low-level API for interacting with relational databases using SQL queries. Unlike
ORM tools, it requires manual handling of SQL and result sets.

Key Features:

●​ Direct SQL execution.


●​ Fine-grained control over database interactions.
●​ Requires handling of connections, statements, and result sets manually.

Example:
java
Copy code
String query = "SELECT * FROM users WHERE name = ?";
try (Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"user", "password");
PreparedStatement stmt = conn.prepareStatement(query)) {

stmt.setString(1, "John");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("email"));
}
}

Comparison Table
Feature JPA Hibernate ORM JDBC

Type Specification Framework (JPA Concept Low-level


Implementation) API

Abstraction High High High Low

SQL Generation Automatic Automatic Automatic (via Manual


tools)

Ease of Use Easy Easy Varies Hard

Database Yes Yes Yes No


Independence

When to Use Standardized Advanced ORM General ORM Fine-graine


ORM needs features requirement d control

When to Use Which One?

Use JPA:

●​ If you want to stick to the standard ORM API.


●​ If you're building a database-independent application.
●​ When you want to leverage Spring Boot's JpaRepository for easy CRUD operations.

Use Hibernate:

●​ If you need advanced features like caching, batch processing, or specific Hibernate-only
capabilities.
●​ If you're already familiar with Hibernate and its HQL.

Use ORM:

●​ When you need to map objects to tables but aren't bound to JPA or Hibernate.
●​ For custom solutions or lightweight ORM requirements.
Use JDBC:

●​ If your application requires fine-grained control over SQL.


●​ When performance is critical, and you want to avoid ORM overhead.
●​ For simple use cases or legacy systems that don't use ORM.

Practical Use Case in Spring Boot


JPA with Hibernate: Default choice for most applications. Spring Boot's auto-configuration
makes it easy to set up.​
properties​
Copy code​
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update

●​

JDBC: Use if you need custom SQL or complex queries that are difficult to achieve with JPA.​
java​
Copy code​
@Autowired
private JdbcTemplate jdbcTemplate;

public List<User> getUsers() {


String query = "SELECT * FROM users";
return jdbcTemplate.query(query, new
BeanPropertyRowMapper<>(User.class));

●​ }

==================

PUT VS POST
In Spring Boot (and RESTful APIs in general), PUT and POST are HTTP methods used to send
data to the server, but they have different purposes and behaviors.

🔁 POST (Create)

●​ Purpose: Used to create a new resource.
●​ Idempotent: Not idempotent (calling multiple times may create multiple resources).
●​ Usage: When you don't know the URI of the resource in advance (server generates it).
●​ Example: Submitting a form to create a new user.​
@PostMapping("/students")
public ResponseEntity<Student> createStudent(@RequestBody Student
student) {
Student saved = studentService.save(student);
return new ResponseEntity<>(saved, HttpStatus.CREATED);
}

🔄 PUT (Update or Create)


●​ Purpose: Used to update an existing resource OR create one at a known URI.​

●​ Idempotent: ✅ Idempotent (same request multiple times results in same output).​


●​ Usage: When client knows the URI (like updating a student by ID).​

●​ Example: Updating a student record.​

@PutMapping("/students/{id}")
public ResponseEntity<Student> updateStudent(@PathVariable Long id,
@RequestBody Student student) {
Student updated = studentService.update(id, student);
return ResponseEntity.ok(updated);
}

🔑 Key Differences:
Feature POST PUT

Used for Create Update (or create at a known URI)

Idempotency No Yes

URI Server decides (e.g., /students) Client provides (e.g., /students/1)

Safe to repeat No (can create duplicates) Yes (same result every time)

✅ When to Use What?


●​ Use POST when creating a new resource (e.g., new user registration).​

●​ Use PUT when updating an existing resource, or creating at a specific location.

—--------------------------------
Links
Interview by code decode LINK

Interview ques LINK

Interview durgesh LINK

Interview Java Techie LINK

Code with durgesh api creation part 1 LINK

“ ” part 2 LINK
Interview ques
1. What is Spring Boot, and how is it different from the Spring Framework?

Explanation:

Spring Boot is a framework built on top of the Spring Framework to simplify the development of
Spring-based applications. It provides:

●​ Auto-configuration: Automatically configures Spring application components based on


the libraries available in the classpath.
●​ Embedded Servers: Comes with embedded servers like Tomcat, Jetty, or Undertow,
eliminating the need for deploying WAR files.
●​ Starter Dependencies: Provides a set of pre-configured dependencies to quickly
bootstrap your application.
●​ Opinionated Defaults: Offers sensible defaults for faster development.

Example:
java
Copy code
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

2. What is the role of @SpringBootApplication?

Explanation:

@SpringBootApplication is a convenience annotation that combines:

●​ @Configuration: Defines beans and their dependencies.


●​ @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration.
●​ @ComponentScan: Scans for components, configurations, and services in the specified
package.

Example:
java
Copy code
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3. What is auto-configuration in Spring Boot? How does it work?

Explanation:

Auto-configuration in Spring Boot attempts to automatically configure your application based on


the dependencies on the classpath. It uses the @EnableAutoConfiguration annotation and
the spring.factories file to identify and load configuration classes.

Key Points:

●​ Enabled by default with @SpringBootApplication.


●​ Can be customized using application.properties or overridden by defining beans
explicitly.

Exclusions can be specified using:​


java​
Copy code​
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

4. How is dependency management handled in Spring Boot?

Explanation:

Spring Boot uses Spring Boot Starters, which are a curated set of dependencies for specific
functionalities. For example:

●​ spring-boot-starter-web: For building web applications.


●​ spring-boot-starter-data-jpa: For JPA-based database access.
●​ spring-boot-starter-security: For security features.

The parent POM (spring-boot-starter-parent) provides:

●​ Default versions for dependencies.


●​ A dependency management section for version conflicts.

Example:
xml
Copy code
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

5. What are Spring Boot Starters? Name some commonly used starters.

Explanation:
Starters are pre-configured dependencies for quickly setting up applications. Common starters
include:

●​ spring-boot-starter-web: For web applications with Tomcat and Spring MVC.


●​ spring-boot-starter-data-jpa: For JPA and Hibernate support.
●​ spring-boot-starter-security: For security.
●​ spring-boot-starter-test: For testing.

6. What is the Spring Boot Actuator?

Explanation:

Spring Boot Actuator provides production-ready features like health checks, metrics, and
monitoring. It exposes endpoints (e.g., /actuator/health, /actuator/metrics) to check
application status.

Example:

Enable Actuator in application.properties:

properties
Copy code
management.endpoints.web.exposure.include=*

Access endpoints like:

bash
Copy code
http://localhost:8080/actuator/health

7. How can you externalize configuration in Spring Boot?

Explanation:

Spring Boot allows configuration to be externalized using:

●​ Properties files: application.properties or application.yml.


●​ Environment variables.
●​ Command-line arguments.

Example:

In application.properties:

properties
Copy code
server.port=8081
In code:

java
Copy code
@Value("${server.port}")
private int port;

8. How do you implement exception handling in Spring Boot?

Explanation:

Use @ControllerAdvice and @ExceptionHandler for centralized exception handling.

Example:
java
Copy code
@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String>
handleResourceNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(),
HttpStatus.NOT_FOUND);
}
}

9. What is the difference between @RestController and @Controller?

Explanation:

●​ @Controller: Used for traditional MVC applications, returns views.


●​ @RestController: Combines @Controller and @ResponseBody. It is used in
REST APIs and returns JSON or XML responses.

Example:
java
Copy code
@RestController
@RequestMapping("/api")
public class MyController {

@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}

10. How do you connect a Spring Boot application to a database?

Explanation:

1.​ Add database dependencies, e.g., spring-boot-starter-data-jpa and the


database driver.

Configure the database in application.properties:​


properties​
Copy code​
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password

2.​
3.​ Use @Entity, @Repository, and JpaRepository for ORM mapping.

11. How does Spring Boot handle logging?

Explanation:

Spring Boot uses SLF4J with Logback as the default logging framework. Logs can be
configured in application.properties:

properties
Copy code
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=app.log

12. How do you secure a Spring Boot application?

Explanation:

Spring Boot provides security using spring-boot-starter-security. Add the dependency


and configure SecurityConfig:

java
Copy code
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}

13. What is the use of profiles in Spring Boot?

Explanation:

Profiles allow separating configurations for different environments (e.g., dev, test, prod). Use
@Profile or spring.profiles.active in application.properties.

14. How does Spring Boot implement caching?

Explanation:

Spring Boot provides caching support via annotations:

●​ @EnableCaching: Enables caching.


●​ @Cacheable: Caches the result of a method.
●​ @CacheEvict: Removes entries from the cache.

15. How do you test a Spring Boot application?

Explanation:

Spring Boot uses spring-boot-starter-test for testing:

●​ Use @SpringBootTest for integration tests.


●​ Use @MockBean and @Mock for mocking dependencies.

Example:​
java​
Copy code​
@SpringBootTest
public class UserServiceTest {

@Autowired
private UserService userService;
@Test
public void testGetUser() {
assertEquals("John", userService.getUser());
}
}

—-------

1. What is Spring Boot and why is it used?

Answer:​
Spring Boot is a framework built on top of the Spring Framework that simplifies the process of
building production-ready Spring applications. It eliminates boilerplate configurations by
providing:

●​ Auto-configuration: Automatically configures your application based on the


dependencies.​

●​ Standalone Applications: No need for external servers; embedded Tomcat/Jetty.​

●​ Production-ready features: Actuator, metrics, health checks.​

●​ Opinionated Defaults: Pre-set configurations that reduce the need for XML.​

2. What are the main features of Spring Boot?

Answer:

●​ Starter Dependencies: Pre-defined Maven/Gradle dependencies to simplify build


configuration.​

●​ Auto Configuration: Automatically configures Spring beans based on classpath


settings.​

●​ Spring Boot CLI: Command-line tool to quickly develop apps using Groovy.​

●​ Embedded Servers: Tomcat, Jetty, or Undertow embedded; no need to deploy WARs.​

●​ Spring Boot Actuator: Provides endpoints for monitoring and managing the application.​

3. What is the difference between Spring and Spring Boot?


Feature Spring Framework Spring Boot

Configuration Manual Auto-configuration

Deployment WAR on external Embedded server


server

Setup Time Longer Faster

Project More complex Simplified with starters


Structure

Monitoring Needs setup Actuator provided

4. What are Spring Boot Starters?

Answer:​
Starters are a set of convenient dependency descriptors you can include in your application.
For example:

●​ spring-boot-starter-web: For building web apps with RESTful services.​

●​ spring-boot-starter-data-jpa: For Spring Data JPA and Hibernate.​


They group commonly used dependencies into one, reducing the need for individual
imports.​

5. What is Spring Boot Auto-Configuration?

Answer:​
Auto-Configuration is a Spring Boot feature that automatically configures beans based on
classpath and project settings. For example, if spring-boot-starter-web is on the
classpath, Spring Boot configures Tomcat and sets up MVC.

@SpringBootApplication // which includes @EnableAutoConfiguration


6. What is @SpringBootApplication annotation?

Answer:​
It is a convenience annotation that combines:

●​ @Configuration: For defining beans.​

●​ @EnableAutoConfiguration: Enables auto-configuration.​

●​ @ComponentScan: Scans the package for components.​

Example:

java

CopyEdit

@SpringBootApplication

public class MyApp {

public static void main(String[] args) {

SpringApplication.run(MyApp.class, args);

7. How does Spring Boot handle application properties?

Answer:​
You can configure settings using:

●​ application.properties​

●​ application.yml​

Common usage:

properties

CopyEdit

server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb

You can also use @Value, @ConfigurationProperties to inject values.

8. What is Spring Boot Actuator?

Answer:​
It provides production-ready features like:

●​ Health checks (/actuator/health)​

●​ Metrics (/actuator/metrics)​

●​ Environment (/actuator/env)​

To enable:

xml

CopyEdit

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

9. How do you implement Exception Handling in Spring Boot?

Answer:​
Use @ControllerAdvice and @ExceptionHandler.

Example:

java

CopyEdit

@ControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String>
handleNotFound(ResourceNotFoundException ex) {

return new ResponseEntity<>(ex.getMessage(),


HttpStatus.NOT_FOUND);

10. What is the use of application.properties and how do you access


values?

Answer:​
Used for external configuration. You can access values via:

●​ @Value("${property.name}")​

●​ @ConfigurationProperties(prefix="custom")​

Example:

properties

CopyEdit

app.name=MyApp

java

CopyEdit

@Value("${app.name}")

private String appName;

11. How do you create a REST controller in Spring Boot?

Answer:​
Using @RestController:

java
CopyEdit

@RestController

@RequestMapping("/api")

public class HelloController {

@GetMapping("/hello")

public String sayHello() {

return "Hello World";

12. What is Spring Boot DevTools?

Answer:​
It enables hot reloading, live reload, and enhanced development-time features. Add this
dependency for it:

xml

CopyEdit

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<scope>runtime</scope>

</dependency>

13. How to enable logging in Spring Boot?

Answer:​
Spring Boot uses SLF4J with Logback by default.

Configure logging level in application.properties:


properties

CopyEdit

logging.level.org.springframework=DEBUG

14. How to create custom starter in Spring Boot?

Answer:​
Steps:

1.​ Create a new Maven project with necessary dependencies.​

2.​ Add spring.factories file under META-INF.​

3.​ Package and use the starter in other projects.​

15. What is the difference between @Component, @Service, @Repository,


and @Controller?

Annotation Purpose

@Component Generic stereotype for any Spring-managed


component

@Service Marks a business service class

@Repository Marks a DAO class; adds JPA exception


translation

@Controller Marks a web controller (used in MVC)

Q1: What is Spring Data JPA?


Answer:​
Spring Data JPA is a part of Spring Data that simplifies JPA-based data access layers. It
reduces boilerplate by providing repository abstractions and automatic query generation.

Q2: What is the difference between CrudRepository, JpaRepository,


and PagingAndSortingRepository?

Interface Description

CrudRepository Basic CRUD operations

PagingAndSortingR Adds pagination and sorting


epository

JpaRepository Extends both above and adds JPA-specific methods


(e.g. flush, deleteInBatch)

Q3: How do you create a custom query in Spring Data JPA?

java

CopyEdit

@Query("SELECT u FROM User u WHERE u.email = ?1")

User findByEmail(String email);

Or using native query:

java

CopyEdit

@Query(value = "SELECT * FROM users WHERE email = ?1",


nativeQuery = true)

User findByEmailNative(String email);


Q4: How do you use @Modifying and @Transactional?

Used for update/delete operations:

java

CopyEdit

@Transactional

@Modifying

@Query("UPDATE User u SET u.active = false WHERE u.lastLogin <


:date")

void deactivateInactiveUsers(@Param("date") LocalDate date);

Q5: What is the use of @Entity, @Table, @Id, @GeneratedValue?

●​ @Entity: Marks class as JPA entity.​

●​ @Table: (Optional) Set table name.​

●​ @Id: Primary key.​

●​ @GeneratedValue: Auto-generation of ID (AUTO, SEQUENCE, IDENTITY).​

🔸 2. Spring Security
Q1: What is Spring Security?

Answer:​
Spring Security is a powerful framework for authentication, authorization, and protection against
common security attacks (CSRF, XSS, etc.).

Q2: How to secure REST APIs using Spring Security?

Use HttpSecurity in a configuration class:

java

CopyEdit
@Override

protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable()

.authorizeRequests()

.antMatchers("/api/public").permitAll()

.anyRequest().authenticated()

.and().httpBasic();

Q3: How does JWT work with Spring Security?

●​ User logs in → JWT token is generated.​

●​ Token is sent in the header for each request.​

●​ A filter (OncePerRequestFilter) validates the token and sets authentication in


SecurityContext.​

Q4: What is CSRF and how to disable it for REST APIs?

CSRF (Cross Site Request Forgery) is disabled for stateless REST APIs:

java

CopyEdit

http.csrf().disable();

Q5: What are roles and authorities in Spring Security?

●​ Role: High-level permission (ROLE_ADMIN)​

●​ Authority: Specific permission (READ_PRIVILEGES)​


🔸 3. RESTful Services
Q1: What are REST principles?

●​ Stateless​

●​ Client-Server​

●​ Uniform Interface​

●​ Cacheable​

●​ Layered System​

●​ Code on Demand (optional)​

Q2: What are common annotations used in REST controllers?

Annotation Purpose

@RestController Combines @Controller +


@ResponseBody

@GetMapping, @PostMapping HTTP verbs

@RequestBody, @PathVariable, Input mapping


@RequestParam

@ResponseEntity Full HTTP response control

Q3: How do you return custom error messages?

Use @ControllerAdvice + @ExceptionHandler.


Q4: What is the difference between @RequestParam and
@PathVariable?

●​ @RequestParam: Query param (e.g. ?id=5)​

●​ @PathVariable: URL part (e.g. /user/5)​

🔸 4. Microservices with Spring Boot


Q1: What are microservices?

Microservices are a way of designing applications as a collection of loosely coupled services,


each owning a specific business capability.

🔸 5. Spring Cloud (Eureka, Config Server, Circuit


Breaker, etc.)
Q1: What is Eureka?

Answer:​
Eureka is a service registry that allows microservices to register themselves and discover other
services dynamically.

Q2: How to setup Eureka Server?

java

CopyEdit

@EnableEurekaServer

@SpringBootApplication

public class EurekaServerApplication {

public static void main(String[] args) {

SpringApplication.run(EurekaServerApplication.class,
args);

}
}

In application.properties:

properties

CopyEdit

server.port=8761

eureka.client.register-with-eureka=false

eureka.client.fetch-registry=false

Q3: What is Spring Cloud Config Server?

Answer:​
Used to externalize and centralize configuration for all microservices.

Setup:

●​ Annotate with @EnableConfigServer​

●​ Point to Git or file system repository​

Q4: What is Circuit Breaker and how do you implement it?

Answer:​
Circuit Breaker prevents a service from making repeated calls to a failed service. Implement
using Resilience4j:

java

CopyEdit

@CircuitBreaker(name = "default", fallbackMethod = "fallback")

public String callRemoteService() {

return restTemplate.getForObject("http://remote-service",
String.class);

}
public String fallback(Throwable t) {

return "Service is down. Try later.";

Q5: What is API Gateway in Spring Cloud?

Answer:​
API Gateway (e.g., Spring Cloud Gateway) acts as a reverse proxy, routing requests to
appropriate microservices and providing:

●​ Routing​

●​ Load balancing​

●​ Authentication​

●​ Rate limiting​

==========================

schenerio based ques

1. Scenario: Application Startup Fails

Question:

Your Spring Boot application fails to start, and the logs show a BeanCreationException.
How would you troubleshoot and resolve the issue?

Explanation:

A BeanCreationException usually occurs when:

●​ A required bean is missing or improperly configured.


●​ Circular dependencies exist between beans.
●​ Property injection fails.

Approach:

1.​ Check Logs:


○​ Look for detailed messages in the stack trace to identify the bean causing the
issue.
2.​ Common Fixes:
○​ Missing Bean: Add the required bean using @Component, @Service, or
@Bean.
○​ Circular Dependency: Use @Lazy or restructure the bean dependencies.
○​ Configuration Issues: Verify @Value annotations or external property files.

Example:​
java​
Copy code​
@Component

public class MyBean {

@Autowired

private AnotherBean anotherBean; // Check if this bean exists.

3.​

2. Scenario: Slow API Response

Question:

A REST API in your Spring Boot application is slow. How would you identify and resolve the
performance bottleneck?

Explanation:

Common causes for slow APIs include:

●​ Inefficient database queries.


●​ Large payloads being processed.
●​ Network latency or serialization overhead.

Approach:

1.​ Profile the Application:


○​ Use tools like Spring Actuator, JProfiler, or VisualVM to identify bottlenecks.
2.​ Database Optimization:
○​ Use @Query in JPA for optimized queries.

Enable query logging to analyze slow queries:​


properties​
Copy code​
spring.jpa.show-sql=true

spring.jpa.properties.hibernate.format_sql=true

○​
3.​ Payload Optimization:
○​ Use pagination for large datasets.
○​ Minimize unnecessary data serialization.
4.​ Asynchronous Processing:

Use @Async for non-blocking API calls:​


java​
Copy code​
@Async

public CompletableFuture<String> processData() {

return CompletableFuture.completedFuture("Processed");

○​

3. Scenario: Multiple Data Sources

Question:

How would you configure and use multiple data sources in a Spring Boot application?

Explanation:

Spring Boot doesn't natively support multiple data sources out of the box, but you can configure
them using:

●​ Separate DataSource beans.


●​ Custom EntityManagerFactory and TransactionManager.

Approach:

Add multiple database configurations in application.properties:​


properties​
Copy code​
spring.datasource.primary.url=jdbc:mysql://localhost:3306/primary_db

spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondary_db

1.​

Define separate configuration classes:​


java​
Copy code​
@Configuration

@Primary

public class PrimaryDataSourceConfig {


@Bean

@ConfigurationProperties(prefix = "spring.datasource.primary")

public DataSource primaryDataSource() {

return DataSourceBuilder.create().build();

@Configuration

public class SecondaryDataSourceConfig {

@Bean

@ConfigurationProperties(prefix = "spring.datasource.secondary")

public DataSource secondaryDataSource() {

return DataSourceBuilder.create().build();

2.​

4. Scenario: File Upload Handling

Question:

How would you handle file uploads in a Spring Boot REST API?

Explanation:

Spring Boot provides built-in support for handling multipart file uploads.

Approach:

Add the required dependency:​


xml​
Copy code​
<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>
</dependency>

1.​

Enable multipart file upload in application.properties:​


properties​
Copy code​
spring.servlet.multipart.enabled=true

spring.servlet.multipart.max-file-size=10MB

spring.servlet.multipart.max-request-size=20MB

2.​

Create a REST endpoint:​


java​
Copy code​
@RestController

@RequestMapping("/files")

public class FileController {

@PostMapping("/upload")

public String uploadFile(@RequestParam("file") MultipartFile file) throws


IOException {

String filename = file.getOriginalFilename();

Files.copy(file.getInputStream(), Paths.get("uploads/" + filename));

return "File uploaded successfully: " + filename;

3.​

5. Scenario: Securing an API Endpoint

Question:

You need to secure specific endpoints in your Spring Boot application. How would you achieve
this?

Explanation:
Use Spring Security to secure endpoints with role-based access control.

Approach:

Add the dependency:​


xml​
Copy code​
<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

1.​

Create a security configuration:​


java​
Copy code​
@Configuration

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override

protected void configure(HttpSecurity http) throws Exception {

http

.authorizeRequests()

.antMatchers("/public/**").permitAll()

.antMatchers("/admin/**").hasRole("ADMIN")

.anyRequest().authenticated()

.and()

.formLogin();

2.​
6. Scenario: Handling Distributed Transactions

Question:

How would you handle distributed transactions in a Spring Boot application?

Explanation:

Distributed transactions span multiple resources (e.g., databases, messaging queues). Use
Spring Boot with JTA (Java Transaction API) for this.

Approach:

Add dependencies for JTA (e.g., Atomikos):​


xml​
Copy code​
<dependency>

<groupId>com.atomikos</groupId>

<artifactId>transactions-jta</artifactId>

</dependency>

1.​

Configure @Transactional with JTA:​


java​
Copy code​
@Service

@Transactional

public class OrderService {

@Autowired

private PaymentService paymentService;

public void processOrder(Order order) {

// Perform database operations across multiple resources

paymentService.processPayment(order);

2.​
7. Scenario: Application Deployment Issues

Question:

Your Spring Boot application works locally but fails after deployment to a server. How do you
debug?

Explanation:

Common causes:

●​ Environment-specific configurations missing.


●​ Port conflicts or external resource issues.

Approach:

1.​ Check Logs:


○​ Look for stack traces in server logs.
2.​ Verify External Configurations:
○​ Use profiles (application-dev.properties,
application-prod.properties).
3.​ Environment Validation:
○​ Check the server’s Java version, network settings, and database connectivity.

8. Scenario: Consuming an External REST API

Question:

How would you consume a REST API in your Spring Boot application?

Explanation:

Spring Boot provides RestTemplate and WebClient for consuming APIs.

Approach:

Using RestTemplate:​
java​
Copy code​
@RestController

public class ApiController {

@Autowired

private RestTemplate restTemplate;


@GetMapping("/consume")

public String consumeApi() {

String url = "https://api.example.com/data";

return restTemplate.getForObject(url, String.class);

1.​

Using WebClient:​
java​
Copy code​
@RestController

public class ApiController {

@Autowired

private WebClient.Builder webClientBuilder;

@GetMapping("/consume")

public Mono<String> consumeApi() {

return webClientBuilder.build()

.get()

.uri("https://api.example.com/data")

.retrieve()

.bodyToMono(String.class);

================

You might also like