Spring Boot
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:
● JDBC allows you to execute SQL queries directly, making it suitable for applications
where you need precise control over database interactions.
● For simple use cases or performance-critical applications, using JDBC directly can be
more lightweight than abstracting operations through JPA or ORM frameworks.
● JDBC is ideal when the application requires complex or custom SQL queries that may
not be easily implemented with higher-level abstractions.
● 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.
java
Copy code
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
By combining JDBC with Spring Boot’s capabilities, you can achieve both simplicity and
powerful database interaction.
==============================
1. Core Annotations
@SpringBootApplication
Example:
javak
Copy code
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Example:
java
Copy code
@Component
public class MyService {
public void performTask() {
System.out.println("Task performed.");
}
}
●
@Service
Example:
java
Copy code
@Service
public class UserService {
public String getUser() {
return "John Doe";
}
}
●
@Repository
Example:
java
Copy code
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
@Controller
Example:
java
Copy code
@Controller
public class HomeController {
@RequestMapping("/")
public String home() {
return "index";
}
}
●
@RestController
Example:
java
Copy code
@RestController
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob", "Charlie");
}
}
Example:
java
Copy code
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
●
@Bean
Example:
java
Copy code
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Value
Example:
java
Copy code
@Value("${app.name}")
private String appName;
●
@PropertySource
Example:
java
Copy code
@Configuration
@PropertySource("classpath:application.properties")
public class PropertyConfig {
}
Example:
java
Copy code
@RestController
@RequestMapping("/api")
public class ApiController {
@RequestMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob");
}
}
Example:
java
Copy code
@RestController
public class UserController {
@GetMapping("/users")
public List<String> getUsers() {
return List.of("Alice", "Bob");
}
}
●
@PathVariable
Example:
java
Copy code
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {
return "User ID: " + id;
}
●
@RequestParam
Example:
java
Copy code
@GetMapping("/search")
public String search(@RequestParam String query) {
return "Search Query: " + query;
}
5. Data Access
@Entity
Example:
java
Copy code
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
●
@Table
● Specifies the table name for an entity.
Example:
java
Copy code
@Entity
@Table(name = "users")
public class User {
}
●
@Id
Example:
java
Copy code
@Id
private Long id;
●
@GeneratedValue
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
}
}
● 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);
}
}
🔁 Propagation Types
Type Description
🔸 Example:
java
CopyEdit
@Transactional(propagation = Propagation.REQUIRES_NEW)
🔐 Isolation Levels
Level Description
🔸 Example:
java
CopyEdit
@Transactional(isolation = Isolation.SERIALIZABLE)
🔄 Rollback Conditions
By default, Spring rolls back on unchecked exceptions (RuntimeException, Error) only.
CopyEdit
@Transactional(rollbackFor = Exception.class)
7. Exception Handling
@ControllerAdvice
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
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.
✅ Example:
java
CopyEdit
@Component
System.out.println("Dog barks");
@Component
System.out.println("Cat meows");
@Component
@Autowired
this.animal = animal;
}
✅ Example:
java
CopyEdit
@Component
@Primary
System.out.println("Dog barks");
@Component
System.out.println("Cat meows");
}
}
@Component
@Autowired
✅ Example:
java
CopyEdit
@Component
@Scope("prototype")
public UserService() {
System.out.println("New UserService instance created");
In this case, each injection or context call to UserService will create a new object.
● Spring creates the bean instance using Java reflection or constructor injection.
java
CopyEdit
2. Populate Properties
java
CopyEdit
bean.setSomeDependency(dep);
java
CopyEdit
setBeanName(String name);
java
CopyEdit
setBeanFactory(BeanFactory factory);
5. Set ApplicationContext
java
CopyEdit
setApplicationContext(ApplicationContext ctx);
java
CopyEdit
postProcessBeforeInitialization(bean, beanName);
7. Initializing Bean
○
○ Or if init-method is defined in XML or @PostConstruct is used.
java
CopyEdit
postProcessAfterInitialization(bean, beanName);
9. Ready to Use
10. Destruction
CopyEdit
[Instantiation]
[Populate Properties]
[Ready to use]
[Container shutdown]
[destroy() / @PreDestroy]
======================
Topics :-
● Spring boot Archetucture -
https://www.geeksforgeeks.org/spring-boot-architecture/?ref=lbp
●
Diff
spring framework vs spring MVC vs spring boot
1. Spring Framework
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:
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;
}
// 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:
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
Key Features:
Example:
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
● 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.
—---------
● 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 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:
Example:
java
Copy code
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
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:
In Spring Boot, you often use Hibernate behind the scenes when working with JPA.
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.
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
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:
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
Use JPA:
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:
●
JDBC: Use if you need custom SQL or complex queries that are difficult to achieve with JPA.
java
Copy code
@Autowired
private JdbcTemplate jdbcTemplate;
● }
==================
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);
}
@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
Idempotency No Yes
Safe to repeat No (can create duplicates) Yes (same result every time)
—--------------------------------
Links
Interview by code decode 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:
Example:
java
Copy code
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Explanation:
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:
Key Points:
Explanation:
Spring Boot uses Spring Boot Starters, which are a curated set of dependencies for specific
functionalities. For example:
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:
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:
properties
Copy code
management.endpoints.web.exposure.include=*
bash
Copy code
http://localhost:8080/actuator/health
Explanation:
Example:
In application.properties:
properties
Copy code
server.port=8081
In code:
java
Copy code
@Value("${server.port}")
private int port;
Explanation:
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);
}
}
Explanation:
Example:
java
Copy code
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}
Explanation:
2.
3. Use @Entity, @Repository, and JpaRepository for ORM mapping.
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
Explanation:
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();
}
}
Explanation:
Profiles allow separating configurations for different environments (e.g., dev, test, prod). Use
@Profile or spring.profiles.active in application.properties.
Explanation:
Explanation:
Example:
java
Copy code
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testGetUser() {
assertEquals("John", userService.getUser());
}
}
—-------
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:
● Opinionated Defaults: Pre-set configurations that reduce the need for XML.
Answer:
● Spring Boot CLI: Command-line tool to quickly develop apps using Groovy.
● Spring Boot Actuator: Provides endpoints for monitoring and managing the application.
Answer:
Starters are a set of convenient dependency descriptors you can include in your application.
For example:
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.
Answer:
It is a convenience annotation that combines:
Example:
java
CopyEdit
@SpringBootApplication
SpringApplication.run(MyApp.class, args);
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
Answer:
It provides production-ready features like:
● Metrics (/actuator/metrics)
● Environment (/actuator/env)
To enable:
xml
CopyEdit
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Answer:
Use @ControllerAdvice and @ExceptionHandler.
Example:
java
CopyEdit
@ControllerAdvice
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String>
handleNotFound(ResourceNotFoundException ex) {
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}")
Answer:
Using @RestController:
java
CopyEdit
@RestController
@RequestMapping("/api")
@GetMapping("/hello")
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>
Answer:
Spring Boot uses SLF4J with Logback by default.
CopyEdit
logging.level.org.springframework=DEBUG
Answer:
Steps:
Annotation Purpose
Interface Description
java
CopyEdit
java
CopyEdit
java
CopyEdit
@Transactional
@Modifying
🔸 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.).
java
CopyEdit
@Override
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/public").permitAll()
.anyRequest().authenticated()
.and().httpBasic();
CSRF (Cross Site Request Forgery) is disabled for stateless REST APIs:
java
CopyEdit
http.csrf().disable();
● Stateless
● Client-Server
● Uniform Interface
● Cacheable
● Layered System
Annotation Purpose
Answer:
Eureka is a service registry that allows microservices to register themselves and discover other
services dynamically.
java
CopyEdit
@EnableEurekaServer
@SpringBootApplication
SpringApplication.run(EurekaServerApplication.class,
args);
}
}
In application.properties:
properties
CopyEdit
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
Answer:
Used to externalize and centralize configuration for all microservices.
Setup:
Answer:
Circuit Breaker prevents a service from making repeated calls to a failed service. Implement
using Resilience4j:
java
CopyEdit
return restTemplate.getForObject("http://remote-service",
String.class);
}
public String fallback(Throwable t) {
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
==========================
Question:
Your Spring Boot application fails to start, and the logs show a BeanCreationException.
How would you troubleshoot and resolve the issue?
Explanation:
Approach:
Example:
java
Copy code
@Component
@Autowired
3.
Question:
A REST API in your Spring Boot application is slow. How would you identify and resolve the
performance bottleneck?
Explanation:
Approach:
spring.jpa.properties.hibernate.format_sql=true
○
3. Payload Optimization:
○ Use pagination for large datasets.
○ Minimize unnecessary data serialization.
4. Asynchronous Processing:
return CompletableFuture.completedFuture("Processed");
○
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:
Approach:
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondary_db
1.
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
return DataSourceBuilder.create().build();
@Configuration
@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
return DataSourceBuilder.create().build();
2.
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:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=20MB
2.
@RequestMapping("/files")
@PostMapping("/upload")
3.
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:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1.
@EnableWebSecurity
@Override
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
2.
6. Scenario: Handling Distributed Transactions
Question:
Explanation:
Distributed transactions span multiple resources (e.g., databases, messaging queues). Use
Spring Boot with JTA (Java Transaction API) for this.
Approach:
<groupId>com.atomikos</groupId>
<artifactId>transactions-jta</artifactId>
</dependency>
1.
@Transactional
@Autowired
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:
Approach:
Question:
How would you consume a REST API in your Spring Boot application?
Explanation:
Approach:
Using RestTemplate:
java
Copy code
@RestController
@Autowired
1.
Using WebClient:
java
Copy code
@RestController
@Autowired
@GetMapping("/consume")
return webClientBuilder.build()
.get()
.uri("https://api.example.com/data")
.retrieve()
.bodyToMono(String.class);
================