馃崈
Spring Boot
Complete
Beginner's Guide + Interview Q&A
Covering All 22 Topics · Code
Examples · Cheat Sheet
Whether you are
just starting your Java journey or preparing for your first Spring Boot
interview, this guide covers everything you need — from the basics all the way
to advanced topics like microservices, security, and messaging. Each section
includes a simple explanation, real code examples, and interview questions with
answers.
1. Introduction to Spring Boot
Spring Boot is an
open-source Java-based framework that helps you build stand-alone,
production-ready applications with very little configuration. Think of it as a
supercharged version of the Spring Framework — it sets up most things
automatically so you can focus on writing your business logic.
Key Features
•
Auto-Configuration: Automatically sets up your app
based on the dependencies you add
•
Embedded Servers: Ships with Tomcat, Jetty, or Undertow
— no external server needed
•
Production-Ready: Built-in health checks, metrics, and
monitoring via Actuator
•
No XML Config: Uses annotations instead of XML, keeping
your code clean
•
Starter Dependencies: Pre-packaged bundles of libraries
for common use cases
Spring Boot vs Spring Framework
|
Aspect |
Spring Framework |
Spring Boot |
|
Setup |
Manual
XML or Java config |
Auto-configuration,
zero XML |
|
Server |
External
servlet container |
Embedded
Tomcat/Jetty/Undertow |
|
Dependencies |
You
manage everything |
Starter
packs handle it |
|
Boilerplate |
A
lot |
Minimal |
|
Learning
Curve |
Steeper |
Beginner-friendly |
|
Build
Output |
WAR
file |
Executable
JAR |
|
Microservices |
Custom
setup needed |
Tailor-made
for it |
Interview Questions
Q: What is Spring Boot and why is it used?
A: Spring Boot is
a framework built on top of Spring that simplifies application development by
providing auto-configuration, embedded servers, and starter dependencies. It is
used because it reduces boilerplate code and gets applications running quickly.
Q: What is the difference between Spring and Spring Boot?
A: Spring requires
manual configuration (XML or Java-based), an external servlet container, and
manual dependency management. Spring Boot automates all of this with
auto-configuration, embedded servers, and starter packs.
Q: What are Spring Boot Starters?
A: Starters are
pre-defined dependency bundles. For example, spring-boot-starter-web includes
Spring MVC, Jackson, and Tomcat — everything needed for a web app in one
dependency.
2. Getting Started
The easiest way to
create a Spring Boot project is using Spring Initializr at start.spring.io. You
choose your language (Java/Kotlin/Groovy), build tool (Maven/Gradle), Spring
Boot version, and which starters you need — then download a ready-to-run project.
Application Entry Point
Every Spring Boot app
starts with a class annotated @SpringBootApplication:
@SpringBootApplication
public class MyApplication {
public static void
main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@SpringBootApplication = @Configuration + @EnableAutoConfiguration +
@ComponentScan
Interview Questions
Q: What does @SpringBootApplication do?
A: It is a
convenience annotation combining @Configuration (marks the class as a source of
bean definitions), @EnableAutoConfiguration (enables Spring Boot's
auto-config), and @ComponentScan (scans for components in the package).
Q: How do you run a Spring Boot application?
A: You can run it
from your IDE, or build a JAR with 'mvn clean package' and then run it with
'java -jar target/myapp.jar'.
3. Core Concepts — Annotations, DI & IoC
Key Annotations
|
Annotation |
Purpose |
|
@Component |
Generic
Spring-managed bean |
|
@Service |
Business
logic layer — specialization of @Component |
|
@Repository |
Data
access layer — also translates DB exceptions |
|
@Controller |
Web
MVC controller — returns views (HTML) |
|
@RestController |
@Controller
+ @ResponseBody — returns JSON/XML directly |
|
@Autowired |
Injects
a dependency automatically by type |
|
@Qualifier |
Specifies
which bean to inject when multiple exist |
|
@Configuration |
Marks
a class as a source of bean definitions |
|
@Bean |
Declares
a single bean inside a @Configuration class |
Dependency Injection Example
@Service
public class OrderService {
private final
PaymentService paymentService;
@Autowired // Constructor injection — recommended
public
OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
public void
placeOrder() {
paymentService.processPayment();
}
}
Inversion of Control (IoC)
IoC means the Spring
container — not your code — controls the creation and wiring of objects. You
define your components; Spring creates them, injects dependencies, and manages
their lifecycle. This results in loosely coupled, testable code.
Interview Questions
Q: What is Dependency Injection?
A: It is a design
pattern where an object's dependencies are provided by an external source
(Spring container) rather than the object creating them itself. This promotes
loose coupling and easier testing.
Q: What are the three types of DI in Spring?
A: Constructor
Injection (preferred — dependencies passed via constructor), Setter Injection
(via setter methods — for optional dependencies), and Field Injection (via
@Autowired directly on fields — convenient but harder to test).
Q: What is @Qualifier used for?
A: When multiple
beans of the same type exist, @Qualifier specifies exactly which one to inject.
For example, @Qualifier('dieselEngine') would inject the DieselEngine bean
rather than PetrolEngine.
4. Configuration
Spring Boot supports
multiple ways to configure your application without touching source code —
property files, YAML files, environment variables, and command-line arguments.
application.properties vs application.yml
# application.properties (key=value style)
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
# application.yml (YAML — cleaner for nested configs)
server:
port: 8081
spring:
datasource:
url:
jdbc:mysql://localhost:3306/mydb
username: root
Property Injection
@Component
public class AppSettings {
@Value("${server.port}")
private int port; // Injects individual value
@Value("${custom.message:Default Message}")
private String
message; // Falls back to default if not
set
}
// For grouped properties, use @ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private String
version;
// Getters &
Setters required
}
Profiles
Profiles let you have
different configs for different environments (dev, test, prod):
# application-dev.properties
spring.datasource.url=jdbc:h2:mem:testdb
# application-prod.properties
spring.datasource.url=jdbc:mysql://prod-server:3306/mydb
# Activate in application.properties:
spring.profiles.active=dev
Interview Questions
Q: What is the difference between @Value and
@ConfigurationProperties?
A: @Value injects
individual properties and is good for simple cases. @ConfigurationProperties
maps a group of related properties to a POJO and supports validation — better
for structured configuration.
Q: What are Spring Profiles?
A: Profiles allow
environment-specific configuration. You create files like
application-dev.properties and activate a profile via
spring.profiles.active=dev. Only beans annotated with matching @Profile will be
loaded.
5. Spring Boot Starters
|
Starter |
What It Includes |
|
spring-boot-starter-web |
Build
REST APIs and web apps with Spring MVC + embedded Tomcat |
|
spring-boot-starter-data-jpa |
JPA/Hibernate
for relational database access |
|
spring-boot-starter-security |
Authentication
& authorization with Spring Security |
|
spring-boot-starter-test |
JUnit
5, Mockito, AssertJ for testing |
|
spring-boot-starter-actuator |
Monitoring
endpoints — health, metrics, env |
|
spring-boot-starter-thymeleaf |
Server-side
HTML templating |
|
spring-boot-starter-validation |
Bean
validation with @NotNull, @Email, etc. |
|
spring-boot-starter-mail |
Send
emails from your app |
Interview Questions
Q: What is a Spring Boot Starter?
A: A starter is a
curated set of compatible dependencies bundled as a single Maven/Gradle
dependency. It removes the need to manually find and version each individual
library.
6. Web Development with Spring MVC
Creating a REST API
@RestController
@RequestMapping("/api/users")
public class UserController {
// GET /api/users/42
@GetMapping("/{id}")
public
ResponseEntity<User> getUser(@PathVariable Long id) {
User user =
userService.findById(id);
if (user == null)
{
return
ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
return
ResponseEntity.ok(user);
}
// POST
/api/users?role=admin
@PostMapping
public
ResponseEntity<String> createUser(
@RequestBody
User user,
@RequestParam(required = false) String role) {
userService.save(user);
return
ResponseEntity.status(HttpStatus.CREATED)
.body("User created: " + user.getName());
}
}
Global Exception Handling
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public
ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
return
ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public
ResponseEntity<String> handleGeneral(Exception ex) {
return
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Something went wrong: " + ex.getMessage());
}
}
Interview Questions
Q: What is the difference between @Controller and
@RestController?
A: @Controller is
used for traditional web apps that return views (HTML via Thymeleaf or JSP).
@RestController = @Controller + @ResponseBody, meaning it automatically
serializes return values to JSON/XML for REST APIs.
Q: What is ResponseEntity and when should you use it?
A: ResponseEntity
lets you customize the full HTTP response — status code, headers, and body. Use
it when you need to return different status codes (like 404 if resource not
found, 201 on creation) instead of always returning 200.
Q: What is @ControllerAdvice?
A: It is a global
exception handler that applies to all controllers. You define @ExceptionHandler
methods inside it to handle specific exceptions consistently across the entire
application.
7. Data Access with Spring Data JPA
Entity & Repository
// Entity = a database table
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters &
Setters
}
// Repository = auto-implemented CRUD operations
public interface UserRepository extends JpaRepository<User,
Long> {
List<User>
findByName(String name); // Spring
generates the SQL
@Query("SELECT u
FROM User u WHERE u.email LIKE %:email%")
List<User>
searchByEmail(@Param("email") String email);
}
// Pagination
Page<User> page = userRepository.findAll(
PageRequest.of(0, 10,
Sort.by("name")));
Transactions
@Service
public class UserService {
@Autowired
private UserRepository
userRepository;
@Transactional // All DB ops here succeed or all roll back
public void
registerUser(User user) {
userRepository.save(user);
// More DB
operations...
}
}
Interview Questions
Q: What is Spring Data JPA?
A: It is a Spring
module that simplifies database access by auto-implementing repository
interfaces. You define an interface extending JpaRepository and Spring
generates all the standard CRUD SQL — no boilerplate DAO code needed.
Q: What does @Transactional do?
A: It ensures that
all database operations within a method succeed or all fail together
(atomicity). If any operation throws an exception, the whole transaction is
rolled back.
Q: What is the difference between JpaRepository and
CrudRepository?
A: CrudRepository
provides basic CRUD operations. JpaRepository extends it with JPA-specific
functionality like pagination, sorting, and batch operations.
8. Database Configuration
H2 In-Memory Database (for Development/Testing)
<!-- pom.xml -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
# application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.h2.console.enabled=true
# Access console at: http://localhost:8080/h2-console
MySQL Setup
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Interview Questions
Q: What is HikariCP?
A: HikariCP is
Spring Boot's default connection pool. It maintains a pool of reusable database
connections for better performance, avoiding the overhead of creating a new
connection for every request.
Q: What is spring.jpa.hibernate.ddl-auto?
A: It controls how
Hibernate manages schema. Common values: 'create' (drops and recreates tables
each run), 'update' (adds new columns/tables), 'validate' (checks schema
without changing it), 'none' (does nothing — for production).
9. Validation
Bean Validation Annotations
public class User {
@NotBlank(message =
"Name is required")
private String name;
@Email(message =
"Must be a valid email")
private String email;
@Min(value = 18,
message = "Must be at least 18")
private int age;
@Size(min = 8, max =
20, message = "Password must be 8-20 characters")
private String
password;
}
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public
ResponseEntity<String> addUser(@Valid @RequestBody User user) {
// @Valid triggers
validation — returns 400 if it fails
return
ResponseEntity.ok("User is valid!");
}
}
Interview Questions
Q: What is the difference between @Valid and @Validated?
A: @Valid (from
javax.validation) triggers basic bean validation on method parameters.
@Validated (Spring-specific) supports validation groups for conditional
validation and can be applied at the class level.
Q: What happens when validation fails?
A: Spring
automatically returns an HTTP 400 Bad Request with a
MethodArgumentNotValidException. You can customize the error response using
@ExceptionHandler or @ControllerAdvice.
10. Security with Spring Security
Basic Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER",
"ADMIN")
.anyRequest().authenticated()
)
.httpBasic();
return
http.build();
}
@Bean
public PasswordEncoder
passwordEncoder() {
return new
BCryptPasswordEncoder(); // Never store
plain-text passwords!
}
}
JWT Authentication Flow
1. User sends
username/password → Server validates and returns a JWT token
2. Client stores the
token and sends it with every request in the Authorization header
3. Server validates
the token on each request — no session stored server-side (stateless)
Role-Based Access Control
@GetMapping("/admin/dashboard")
@PreAuthorize("hasRole('ADMIN')") // Only ADMIN can access
public String adminDashboard() {
return "Welcome,
Admin!";
}
// Enable method security at config class level:
@EnableMethodSecurity
public class MethodSecurityConfig { }
Interview Questions
Q: What is Spring Security?
A: Spring Security
is a framework for authentication (verifying who the user is) and authorization
(what they can access). It integrates with Spring Boot to secure REST APIs and
web apps.
Q: Why should passwords be hashed and not stored as plain
text?
A: Plain-text
passwords are a security risk if the database is compromised. BCrypt hashing
transforms a password into an irreversible hash, so even if data is stolen, the
original password cannot be recovered.
Q: What is JWT and why use it?
A: JWT (JSON Web
Token) is a compact, self-contained token for authentication. It is used in
stateless REST APIs because the server does not need to store session data —
the token itself carries user information.
11. Testing in Spring Boot
Unit Test with JUnit + Mockito
class OrderServiceTest {
@Mock
PaymentService
paymentService; // Mock — not real
implementation
@InjectMocks
OrderService
orderService; // Subject under test
@BeforeEach
void init() {
MockitoAnnotations.openMocks(this); }
@Test
void testPlaceOrder()
{
when(paymentService.pay()).thenReturn(true); // Define mock behaviour
assertTrue(orderService.placeOrder()); // Test the result
}
}
Web Layer Test with @WebMvcTest
@WebMvcTest(UserController.class) // Only loads web layer
class UserControllerTest {
@Autowired
private MockMvc
mockMvc;
@Test
void testGetUser()
throws Exception {
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
Interview Questions
Q: What is the difference between @SpringBootTest and
@WebMvcTest?
A: @SpringBootTest
loads the entire application context — good for integration tests. @WebMvcTest
only loads the web layer (controllers) and is faster for testing REST endpoints
in isolation.
Q: What is Mockito used for?
A: Mockito creates
mock (fake) objects that simulate real dependencies. This lets you test a class
in isolation without needing a real database, HTTP call, or other external
service.
Q: What is @DataJpaTest?
A: It loads only
the JPA-related components and uses an in-memory H2 database by default. It is
used for testing repository layer in isolation and rolls back transactions
after each test.
12. Logging
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
public class DemoController {
private static final
Logger logger =
LoggerFactory.getLogger(DemoController.class);
@GetMapping("/test")
public String test() {
logger.info("Request received for /test");
logger.warn("Something might be wrong");
logger.error("Something went wrong!");
return "Check
your logs";
}
}
# application.properties
logging.level.root=INFO
logging.level.com.example.myapp=DEBUG # More detail for your package
logging.file.name=app.log # Write logs to a file
Interview Questions
Q: What is SLF4J?
A: SLF4J (Simple
Logging Facade for Java) is an abstraction layer for logging frameworks. Spring
Boot uses it with Logback as the default implementation. Using SLF4J means you
can switch the underlying logging framework without changing your code.
Q: What are the log levels in order?
A: TRACE (most
detailed) → DEBUG → INFO → WARN → ERROR (least detailed/most severe). Setting a
level means all messages at that level and above will be shown.
13. Actuator & Monitoring
Spring Boot Actuator
adds production-ready monitoring endpoints to your app with minimal setup.
<!-- Add to pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
# Expose all endpoints (restrict in production!)
management.endpoints.web.exposure.include=*
|
Endpoint |
What It Shows |
|
/actuator/health |
Application
health status (UP/DOWN) |
|
/actuator/info |
Custom
app info |
|
/actuator/metrics |
System
metrics — memory, CPU, requests |
|
/actuator/beans |
All
registered Spring beans |
|
/actuator/env |
All
environment properties |
|
/actuator/mappings |
All
HTTP endpoint mappings |
Interview Questions
Q: What is Spring Boot Actuator?
A: Actuator
exposes built-in HTTP endpoints to monitor and manage your running application
— checking health, viewing metrics, listing beans, and more. It is essential
for production observability.
Q: How do you integrate Actuator with Prometheus/Grafana?
A: Add
micrometer-registry-prometheus dependency, expose the /actuator/prometheus
endpoint, configure Prometheus to scrape it, then visualize the data in Grafana
dashboards.
14. Error Handling
Spring Boot returns a
default JSON error response for REST APIs. You can fully customize this with
@ControllerAdvice (covered in Section 6). Best practices include:
•
Use @ResponseStatus on exception classes to bind HTTP
status codes
•
Always log exceptions for debugging
•
Return meaningful messages — hide sensitive stack
traces in production
•
For HTML apps, place custom error pages at
/resources/public/error/404.html
Interview Questions
Q: What is the default error response from Spring Boot?
A: Spring Boot
returns a JSON object with timestamp, status code, error message, and path. For
browser requests, it shows a 'Whitelabel Error Page'. Both can be customized.
15. Developer Tools (DevTools)
Spring Boot DevTools
speeds up development with automatic application restarts and browser live
reload.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<!-- Disabled automatically in production -->
</dependency>
•
Auto Restart: Detects classpath changes and restarts
the app automatically
•
Live Reload: Refreshes the browser when static files
change (needs browser extension)
•
Cache Disabling: Turns off template caching so changes
are reflected immediately
Interview Questions
Q: What is the difference between auto-restart and live
reload in DevTools?
A: Auto-restart
restarts the Spring application context when Java class files change. Live
Reload refreshes the browser when static resources (HTML, CSS, JS) change. They
solve different problems — one for backend, one for frontend.
16. Caching
@SpringBootApplication
@EnableCaching // Step 1:
Enable caching
public class MyApp { }
@Service
public class ProductService {
// Step 2: Cache the
result — same id = skip method, return cached value
@Cacheable("products")
public Product
getProductById(Long id) {
return
productRepository.findById(id).orElse(null);
}
// Step 3: Clear cache
when data changes
@CacheEvict(value =
"products", key = "#id")
public void
deleteProduct(Long id) {
productRepository.deleteById(id);
}
}
Cache Providers
|
Provider |
When to Use |
|
Simple
(default) |
In-memory
ConcurrentHashMap — good for development |
|
Caffeine |
Fast,
feature-rich in-memory cache with expiry and size limits |
|
Ehcache |
Java-based
cache with disk overflow support |
|
Redis |
Distributed
cache — perfect for microservices and clustered apps |
Interview Questions
Q: What is @Cacheable and how does it work?
A: @Cacheable
marks a method so its return value is stored in a cache. On the first call, the
method executes and the result is cached. On subsequent calls with the same
parameters, the cached value is returned without executing the method again.
17. Scheduling & Asynchronous Execution
@SpringBootApplication
@EnableScheduling //
Required for @Scheduled
@EnableAsync //
Required for @Async
public class MyApp { }
@Component
public class ScheduledTasks {
@Scheduled(fixedRate =
5000) // Every 5 seconds
public void
checkStatus() { ... }
@Scheduled(cron =
"0 0 9 * * ?") // Every day
at 9 AM
public void
dailyReport() { ... }
}
@Service
public class EmailService {
@Async // Runs in a background thread — caller is
not blocked
public void
sendWelcomeEmail(String to) {
// This runs
asynchronously
}
}
Interview Questions
Q: What is the difference between @Scheduled fixedRate and
fixedDelay?
A: fixedRate runs
the task at a fixed interval regardless of how long it takes (e.g., every 5
seconds from start). fixedDelay waits for the task to finish, then waits the
delay before starting again.
Q: Why must @Async methods be called from another bean?
A: Spring applies
@Async using a proxy. If you call an @Async method from within the same class,
it bypasses the proxy and runs synchronously. It must be called from a
different Spring bean for the async behavior to work.
18. Messaging — RabbitMQ, Kafka & JMS
Messaging enables
asynchronous, decoupled communication between services — essential for
microservices.
RabbitMQ (AMQP)
// Producer
@Service
public class MessageProducer {
@Autowired private
RabbitTemplate rabbitTemplate;
public void
send(String message) {
rabbitTemplate.convertAndSend("myQueue", message);
}
}
// Consumer
@Component
public class MessageConsumer {
@RabbitListener(queues
= "myQueue")
public void
receive(String message) {
System.out.println("Received:
" + message);
}
}
Apache Kafka
// Producer
@Service
public class KafkaProducer {
@Autowired private
KafkaTemplate<String, String> kafkaTemplate;
public void
send(String message) {
kafkaTemplate.send("myTopic", message);
}
}
// Consumer
@Component
public class KafkaConsumer {
@KafkaListener(topics
= "myTopic", groupId = "my-group")
public void
listen(String message) {
System.out.println("From Kafka: " + message);
}
}
Interview Questions
Q: What is the difference between RabbitMQ and Kafka?
A: RabbitMQ is a
traditional message broker using AMQP — good for task queues and reliable
message delivery. Kafka is a distributed event streaming platform — ideal for
high-throughput, event log, and real-time data pipelines.
19. File Upload & Download
@RestController
@RequestMapping("/files")
public class FileController {
// Upload
@PostMapping("/upload")
public
ResponseEntity<String> upload(@RequestParam("file")
MultipartFile file)
throws
IOException {
Path path =
Paths.get("uploads/" + file.getOriginalFilename());
Files.createDirectories(path.getParent());
Files.write(path,
file.getBytes());
return
ResponseEntity.ok("Uploaded: " + file.getOriginalFilename());
}
// Download
@GetMapping("/download/{filename}")
public
ResponseEntity<Resource> download(@PathVariable String filename)
throws
IOException {
Path path =
Paths.get("uploads/" + filename);
Resource resource
= new UrlResource(path.toUri());
return
ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename="" + filename + """)
.body(resource);
}
}
Security Tip: Always validate file type, size, and sanitize filenames to
prevent directory traversal attacks.
Interview Questions
Q: How do you limit upload file size in Spring Boot?
A: Set
spring.servlet.multipart.max-file-size=5MB and
spring.servlet.multipart.max-request-size=10MB in application.properties.
Spring will reject files exceeding these limits with a MaxUploadSizeExceededException.
20. Frontend Integration
Serving Static Files
Place HTML, CSS, and
JS files in src/main/resources/static/ — Spring Boot serves them automatically
at the root URL (e.g., /index.html).
Thymeleaf Templating
@Controller
public class HomeController {
@GetMapping("/home")
public String
home(Model model) {
model.addAttribute("message", "Hello from Spring
Boot!");
return
"home"; // resolves to
templates/home.html
}
}
<!-- templates/home.html -->
<h1 th:text="${message}"></h1> <!-- Renders server-side -->
Enabling CORS (for React/Angular frontends)
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void
addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000") // React dev server
.allowedMethods("GET", "POST", "PUT",
"DELETE");
}
}
Interview Questions
Q: What is CORS and why is it needed?
A: CORS
(Cross-Origin Resource Sharing) is a browser security mechanism that blocks
requests from a different origin. When your React app on localhost:3000 calls a
Spring Boot API on localhost:8080, the browser blocks it unless the server
explicitly allows it via CORS headers.
21. Build & Deployment
Building & Running a JAR
# Build
mvn clean package
# Run
java -jar target/myapp-0.0.1-SNAPSHOT.jar
# With a specific profile
java -jar myapp.jar --spring.profiles.active=prod
Dockerizing Your App
# Dockerfile
FROM openjdk:21
COPY target/myapp.jar app.jar
ENTRYPOINT ["java", "-jar",
"/app.jar"]
# Build & Run
docker build -t myapp .
docker run -p 8080:8080 myapp
Interview Questions
Q: What is the difference between a JAR and WAR in Spring
Boot?
A: JAR (default)
is a self-contained executable with an embedded server — run with 'java -jar'.
WAR is a web archive deployed to an external server (like Tomcat). Spring Boot
recommends JAR for microservices.
Q: How do you Dockerize a Spring Boot application?
A: Write a
Dockerfile that copies the built JAR into an OpenJDK image and sets the entry
point. Build with 'docker build', run with 'docker run'. For production, use
multi-stage builds to keep the image size small.
22. Advanced Topics — Microservices & More
Spring Cloud Building Blocks
|
Component |
Purpose |
|
Eureka |
Service
Discovery — services register themselves so others can find them by name |
|
Spring
Cloud Gateway |
API
Gateway — single entry point that routes requests to services |
|
Config
Server |
Centralized
external configuration for all microservices from a Git repo |
|
Resilience4j |
Circuit
Breaker — returns a fallback if a downstream service fails |
|
Spring
Cloud LoadBalancer |
Client-side
load balancing across multiple instances |
Circuit Breaker Pattern
@CircuitBreaker(name = "productService",
fallbackMethod = "fallback")
public String getProduct(Long id) {
// Calls external
product-service
return
restTemplate.getForObject(
"http://product-service/api/products/" + id, String.class);
}
// Called automatically if product-service is down
public String fallback(Long id, Throwable t) {
return "Product
service is unavailable. Please try again later.";
}
Application Events
// 1. Define custom event
public class UserCreatedEvent extends ApplicationEvent {
private String email;
public
UserCreatedEvent(Object source, String email) {
super(source);
this.email =
email;
}
}
// 2. Publish it
publisher.publishEvent(new UserCreatedEvent(this,
"user@example.com"));
// 3. Listen to it
@Component
public class EmailListener {
@EventListener
public void
onUserCreated(UserCreatedEvent event) {
// Send welcome
email
}
}
Interview Questions
Q: What is a Circuit Breaker pattern?
A: When a service
keeps failing, calling it wastes resources. A Circuit Breaker opens after a
threshold of failures, returning a fast fallback response instead of waiting.
After a timeout, it tries again. This prevents cascading failures across
microservices.
Q: What is Service Discovery (Eureka)?
A: In a
microservices system, services start and stop dynamically. Eureka lets services
register themselves and discover each other by name instead of hardcoded IP
addresses. Services query Eureka to find where other services are running.
Q: What is a Config Server?
A: Spring Cloud
Config Server provides a centralized place (usually backed by a Git repository)
to store configuration for all microservices. This avoids duplicating config in
each service and makes environment-specific settings easy to manage.
馃搵
Spring Boot Quick Cheat Sheet
Your
go-to reference for the most important annotations, configs, and commands
Stereotype Annotations
|
Annotation |
Layer |
Returns JSON? |
|
@Component |
Generic / Any |
No |
|
@Service |
Business Logic |
No |
|
@Repository |
Data / DAO |
No |
|
@Controller |
Web / View |
No (uses View Resolver) |
|
@RestController |
Web / REST API |
Yes (JSON/XML) |
Most Used Annotations — At a Glance
|
Annotation |
What It Does |
|
@SpringBootApplication |
Entry
point — combines @Config + @EnableAutoConfig + @ComponentScan |
|
@Autowired |
Inject
a dependency automatically |
|
@Value |
Inject
a single property value |
|
@GetMapping
/ @PostMapping |
Map
HTTP GET / POST to a method |
|
@PathVariable |
Extract
value from URL path /users/{id} |
|
@RequestParam |
Extract
query param from URL ?name=John |
|
@RequestBody |
Deserialize
JSON request body into object |
|
@ResponseBody |
Serialize
return value to JSON response |
|
@Transactional |
Wrap
method in a DB transaction |
|
@Cacheable |
Cache
the method's return value |
|
@Scheduled |
Run
method on a schedule / cron |
|
@Async |
Run
method in a background thread |
|
@Valid
/ @Validated |
Trigger
bean validation |
|
@Profile |
Activate
bean only for a specific environment |
|
@ControllerAdvice |
Global
exception handler for all controllers |
Common application.properties Settings
# Server
server.port=8080
# Database (MySQL)
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# Logging
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=app.log
# Actuator
management.endpoints.web.exposure.include=health,info,metrics
# Profiles
spring.profiles.active=dev
# File Upload
spring.servlet.multipart.max-file-size=5MB
# Cache (Caffeine)
spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=1000,expireAfterAccess=5m
Spring Boot Layers — Quick Reference
|
Layer |
Responsibility |
|
Controller
/ @RestController |
Handles
HTTP requests, calls Service layer |
|
Service
/ @Service |
Business
logic — orchestrates data and operations |
|
Repository
/ @Repository |
Data
access — talks directly to the database |
|
Entity
/ @Entity |
Java
class mapped to a database table |
|
Configuration
/ @Configuration |
Bean
definitions and app configuration |
|
DTO
(Data Transfer Object) |
Object
used to send/receive data via API (not the Entity) |
Useful Maven Commands
mvn clean package
# Build a JAR
mvn spring-boot:run
# Run without building JAR first
mvn test
# Run all tests
mvn clean install -DskipTests
# Build, skip tests
Happy Coding!
馃崈
You now have a complete Spring
Boot reference — from your first @SpringBootApplication to microservices with
Spring Cloud.