100 Most Frequently Asked Spring Boot Interview Questions & Answers
1. Spring Boot Fundamentals
1. What is Spring Boot?
Answer:
Spring Boot is a framework built on top of the Spring Framework that simplifies the development of production-ready Java applications.
Its key features include:
- Auto-configuration
- Starter dependencies
- Embedded servers
- Production-ready Actuator
- Externalized configuration
- Minimal XML configuration
- Convention over configuration
For example:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. What are the main advantages of Spring Boot?
Answer:
- Auto-configuration
- Starter dependencies
- Embedded Tomcat/Jetty/Undertow
- Spring Boot Actuator
- Externalized configuration
- Easy integration with Spring modules
- Minimal configuration
- Production-ready features
- Easy testing
- Excellent microservices support
3. What is the difference between Spring and Spring Boot?
| Spring | Spring Boot |
|---|---|
| Core application framework | Built on Spring |
| More configuration required | Convention over configuration |
| Traditionally requires external server | Embedded server supported |
| Dependency management is manual | Starters simplify dependencies |
| No built-in production monitoring | Actuator available |
| More setup | Rapid application development |
Interview tip: Spring Boot does not replace Spring. It simplifies using Spring.
4. What is @SpringBootApplication?
Answer:
@SpringBootApplication is a composite annotation that combines:
@Configuration
@EnableAutoConfiguration
@ComponentScan
Therefore:
Java
@SpringBootApplication
essentially tells Spring Boot to:
- Treat the class as a configuration class
- Enable auto-configuration
- Scan for Spring components
5. What does @EnableAutoConfiguration do?
Answer:
It tells Spring Boot to automatically configure the application based on:
- Dependencies available on the classpath
- Existing beans
- Application properties
- Auto-configuration conditions
For example, if Spring MVC is on the classpath, Spring Boot can automatically configure:
- DispatcherServlet
- MVC infrastructure
- JSON conversion
- Embedded server integration
6. What is Spring Boot auto-configuration?
Answer:
Auto-configuration automatically configures Spring components based on the application’s environment.
For example, if you include:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Spring Boot can automatically configure:
- DataSource
- EntityManagerFactory
- Transaction infrastructure
- Hibernate integration
7. How does Spring Boot auto-configuration work internally?
Answer:
Spring Boot evaluates auto-configuration classes using conditional annotations such as:
@ConditionalOnClass
@ConditionalOnMissingBean
@ConditionalOnProperty
@ConditionalOnBean
For example:
@ConditionalOnClass(DataSource.class)
@ConditionalOnMissingBean(DataSource.class)
means the configuration is applied when a DataSource class exists and the application hasn’t already defined one.
8. How can you disable a specific auto-configuration?
Answer:
Using:
@SpringBootApplication(
exclude = DataSourceAutoConfiguration.class
)
or:
spring.autoconfigure.exclude=\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
9. What are Spring Boot Starter dependencies?
Answer:
Starters are convenient dependency descriptors that group commonly required dependencies.
For example:
XML
spring-boot-starter-web
typically brings dependencies required for:
- Spring MVC
- JSON processing
- Embedded web server
Other examples include:
spring-boot-starter-data-jpa
spring-boot-starter-security
spring-boot-starter-validation
spring-boot-starter-test
10. What is the purpose of spring-boot-starter-parent?
Answer:
It provides useful Maven defaults, including:
- Dependency management
- Plugin configuration
- Compatible dependency versions
- Maven defaults
Modern projects can also use Spring Boot’s dependency management without necessarily inheriting from the parent POM.
2. Dependency Injection and Beans
11. What is Dependency Injection?
Answer:
Dependency Injection means an object’s dependencies are provided by an external container rather than being created by the object itself.
Instead of:
Java
UserRepository repository = new UserRepository();
we use:
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
}
Spring creates and injects the dependency.
12. Why is constructor injection preferred?
Answer:
Constructor injection provides:
- Immutable dependencies
- Easier unit testing
- Explicit dependencies
- Better null-safety
- No reflection-based field injection requirement
- Easier detection of circular dependencies
Preferred:
public UserService(UserRepository repository) {
this.repository = repository;
}
rather than:
@Autowired
private UserRepository repository;
13. What is a Spring Bean?
Answer:
A Spring Bean is an object managed by the Spring IoC container.
Example:
@Service
public class UserService {
}
Spring creates and manages the lifecycle of the UserService object.
14. What is the Spring IoC container?
Answer:
The IoC container is responsible for:
- Creating beans
- Configuring beans
- Injecting dependencies
- Managing bean lifecycle
- Maintaining bean scopes
Common container implementations include:
ApplicationContext
BeanFactory
15. What is the difference between @Component, @Service, and @Repository?
Answer:
All are Spring stereotype annotations.
Java
@Component
General-purpose Spring component.
Java
@Service
Used for service/business logic.
Java
@Repository
Used for persistence/data-access components and provides exception translation.
Technically, @Service and @Repository are specialized forms of @Component.
16. What is @Controller?
Answer:
@Controller identifies a Spring MVC controller that handles HTTP requests.
Example:
@Controller
public class UserController {
}
When returning view names, it is commonly used with server-side rendering.
17. What is @RestController?
Answer:
@RestController combines:
@Controller
@ResponseBody
It is typically used to build REST APIs.
Example:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return service.findById(id);
}
}
18. What is @Bean?
Answer:
@Bean explicitly declares an object as a Spring Bean.
@Configuration
public class AppConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
Spring manages the returned object.
19. What is @Configuration?
Answer:
@Configuration indicates that a class contains Spring bean definitions.
Example:
@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() {
// configuration
}
}
20. What happens if multiple beans of the same type exist?
Answer:
Spring may not know which bean to inject.
For example:
@Bean
public PaymentService stripeService() {}
@Bean
public PaymentService paypalService() {}
You can resolve ambiguity using:
Java
@Qualifier("stripeService")
or:
Java
@Primary
3. Configuration
21. What is externalized configuration?
Answer:
Externalized configuration means application settings are kept outside compiled Java code.
For example:
server.port=8081
spring.datasource.url=jdbc:postgresql://localhost/app
This allows configuration to vary between:
Development
Testing
Staging
Production
without rebuilding the application.
22. What is the difference between application.properties and application.yml?
Answer:
Both provide application configuration.
Properties:
server.port=8080
spring.datasource.url=jdbc:postgresql://localhost/db
YAML:
server:
port: 8080
spring:
datasource:
url: jdbc:postgresql://localhost/db
YAML is often easier to read for hierarchical configuration.
23. What are Spring Profiles?
Answer:
Profiles allow different configurations for different environments.
For example:
application-dev.yml
application-test.yml
application-prod.yml
Activate one with:
properties
spring.profiles.active=prod
24. How do you access configuration properties?
Answer:
Using @Value:
@Value("${app.name}")
private String appName;
For groups of related configuration, @ConfigurationProperties is generally preferable.
25. What is @ConfigurationProperties?
Answer:
It binds external configuration to a strongly typed Java object.
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private int timeout;
}
Configuration:
app:
name: MyApplication
timeout: 30
This is preferable to having many individual @Value fields.
26. What is the difference between @Value and @ConfigurationProperties?
Answer:
@Value | @ConfigurationProperties |
|---|---|
| Good for individual values | Good for groups of values |
| SpEL supported | Strongly typed |
| Less structured | Better configuration model |
| More difficult to validate | Supports validation |
| Useful for simple cases | Preferred for complex configuration |
27. What is Spring Boot’s configuration property precedence?
Answer:
Spring Boot supports multiple configuration sources, including:
- Default properties
application.properties- Profile-specific properties
- Environment variables
- System properties
- Command-line arguments
Higher-precedence sources can override lower-precedence ones.
28. How do you pass configuration using environment variables?
Answer:
For example:
Bash
export SERVER_PORT=8081
Spring Boot maps environment variables to configuration properties.
This is particularly useful in:
- Docker
- Kubernetes
- Cloud deployments
- CI/CD pipelines
29. How should secrets be managed?
Answer:
Do not hard-code secrets:
properties
db.password=MyPassword123
Instead use:
- Environment variables
- Kubernetes Secrets
- AWS Secrets Manager
- Azure Key Vault
- HashiCorp Vault
- GCP Secret Manager
A production application should separate application configuration from secret management.
30. What is CommandLineRunner?
Answer:
It allows code to execute after the Spring application starts.
@Bean
CommandLineRunner runner() {
return args -> {
System.out.println("Application started");
};
}
It is useful for initialization tasks and command-line applications.
4. REST API and Spring MVC
31. How do you create a REST API in Spring Boot?
Answer:
Use @RestController:
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return service.findById(id);
}
}
32. What is @RequestMapping?
Answer:
It maps HTTP requests to controller methods or classes.
Java
@RequestMapping("/api/users")
can define a common base path.
33. What are @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping?
Answer:
They are specialized request mappings.
GET → retrieve
POST → create
PUT → replace/update
PATCH → partial update
DELETE → remove
Example:
@PostMapping
public User create(@RequestBody User user) {
return service.create(user);
}
34. What is @PathVariable?
Answer:
It extracts a value from the URL path.
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
}
Request:
GET /users/123
id = 123.
35. What is @RequestParam?
Answer:
It extracts query parameters.
@GetMapping("/users")
public List<User> search(
@RequestParam String name) {
}
Request:
GET /users?name=Bill
36. What is @RequestBody?
Answer:
It converts an HTTP request body, typically JSON, into a Java object.
@PostMapping
public User create(@RequestBody CreateUserRequest request) {
}
37. What is ResponseEntity?
Answer:
ResponseEntity provides control over:
- HTTP status
- Headers
- Response body
Example:
return ResponseEntity
.status(HttpStatus.CREATED)
.body(user);
38. How do you handle exceptions globally?
Answer:
Use:
Java
@RestControllerAdvice
Example:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<?> handle(UserNotFoundException ex) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
}
39. What is @ControllerAdvice?
Answer:
It allows cross-cutting controller behavior such as:
- Exception handling
- Model configuration
- Data binding configuration
For REST APIs, @RestControllerAdvice is commonly used.
40. How do you validate REST request data?
Answer:
Use Jakarta Bean Validation.
public class CreateUserRequest {
@NotBlank
private String name;
@Email
private String email;
}
Then:
@PostMapping
public User create(
@Valid @RequestBody CreateUserRequest request) {
}
5. Spring Data JPA
41. What is Spring Data JPA?
Answer:
Spring Data JPA simplifies database access using JPA repositories.
Example:
public interface UserRepository
extends JpaRepository<User, Long> {
}
You get operations such as:
save()
findById()
findAll()
delete()
existsById()
without implementing them manually.
42. What is JPA?
Answer:
JPA, Jakarta Persistence API, is a specification for object-relational mapping.
It defines how Java objects map to relational database tables.
Hibernate is one of the most commonly used JPA implementations.
43. What is Hibernate?
Answer:
Hibernate is an ORM framework and a JPA implementation.
It maps:
Java objects ↔ Database tables
and handles operations such as:
- SQL generation
- Persistence context
- Entity lifecycle
- Lazy loading
- Dirty checking
44. What is an Entity?
Answer:
An entity is a Java class mapped to a database table.
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
}
45. What is the difference between CrudRepository and JpaRepository?
Answer:
CrudRepository provides basic CRUD operations.
JpaRepository extends the repository hierarchy and provides additional JPA-oriented capabilities, including pagination/sorting support through inherited interfaces and JPA-specific methods.
For typical Spring Boot JPA applications:
Java
JpaRepository<User, Long>
is commonly used.
46. What are derived query methods?
Answer:
Spring Data can generate queries from method names.
Example:
Java
List<User> findByLastName(String lastName);
Or:
Java
List<User> findByAgeGreaterThan(int age);
Spring Data derives the query automatically.
47. What is @Query?
Answer:
@Query allows developers to define custom JPQL or native SQL queries.
@Query("""
select u
from User u
where u.email = :email
""")
Optional<User> findByEmail(
@Param("email") String email);
48. What is lazy loading?
Answer:
Lazy loading means an associated entity is loaded only when it is accessed.
Example:
@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;
This can improve performance but may cause LazyInitializationException if accessed outside the appropriate persistence context.
49. What is eager loading?
Answer:
Eager loading loads the associated data immediately.
Java
@ManyToOne(fetch = FetchType.EAGER)
Eager relationships can cause unnecessary database queries and large object graphs, so they should be used carefully.
50. What is the N+1 query problem?
Answer:
Suppose we retrieve:
1 query → retrieve 100 users
100 queries → retrieve orders for each user
Total:
101 queries
This is the N+1 problem.
Solutions include:
JOIN FETCH- Entity graphs
- Batch fetching
- DTO projections
- Carefully designed queries
6. Transactions
51. What is @Transactional?
Answer:
@Transactional defines a transactional boundary.
@Transactional
public void transferMoney(...) {
debit();
credit();
}
If an appropriate runtime exception causes rollback, the transaction is rolled back.
52. Where should @Transactional normally be used?
Answer:
Usually at the service layer, where a business operation is represented.
@Service
public class PaymentService {
@Transactional
public void transfer(...) {
...
}
}
This keeps transaction boundaries aligned with business operations.
53. What are transaction propagation modes?
Answer:
Common propagation modes include:
REQUIRED
REQUIRES_NEW
SUPPORTS
MANDATORY
NOT_SUPPORTED
NEVER
NESTED
Most applications primarily use:
Java
Propagation.REQUIRED
which joins an existing transaction or creates a new one.
54. What is transaction isolation?
Answer:
Isolation determines how transactions interact with each other’s changes.
Common levels:
READ_UNCOMMITTED
READ_COMMITTED
REPEATABLE_READ
SERIALIZABLE
Higher isolation generally provides stronger consistency but may reduce concurrency.
55. Does @Transactional always roll back on exceptions?
Answer:
Not automatically for every exception.
By default, Spring typically rolls back for:
RuntimeExceptionError
Checked exceptions generally do not trigger rollback by default.
You can specify:
Java
@Transactional(rollbackFor = Exception.class)
56. What is transaction propagation?
Answer:
Propagation defines how a method participates in an existing transaction.
For example:
Java
@Transactional(propagation = Propagation.REQUIRES_NEW)
suspends the current transaction and executes the method in a new transaction.
57. What is the self-invocation problem with @Transactional?
Answer:
Spring’s transaction management commonly uses proxies.
If a method calls another transactional method on the same object:
Java
this.transactionalMethod();
the call may bypass the Spring proxy, meaning the transactional advice is not applied as expected.
A common solution is to move the transactional operation into another Spring bean or otherwise structure the call through the proxy.
7. Spring Security
58. What is Spring Security?
Answer:
Spring Security provides authentication and authorization functionality for Spring applications.
It supports:
- Username/password authentication
- OAuth2
- OpenID Connect
- JWT
- Method-level security
- CSRF protection
- Session management
- Role/authority-based authorization
59. What is the difference between authentication and authorization?
Answer:
Authentication:
Who are you?
Authorization:
What are you allowed to do?
Example:
Authentication → Bill successfully logs in
Authorization → Bill can access /admin
60. What is a SecurityFilterChain?
Answer:
It defines Spring Security’s HTTP security configuration.
Modern Spring Security uses bean-based configuration:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
61. What is JWT authentication?
Answer:
JWT, or JSON Web Token, is commonly used for stateless authentication.
Typical flow:
Login
↓
Authentication server
↓
JWT
↓
Client
↓
Authorization: Bearer <token>
↓
API validates JWT
The server does not need to maintain traditional server-side session state for each request.
62. What is CSRF?
Answer:
Cross-Site Request Forgery tricks an authenticated browser into sending an unwanted request.
CSRF protection is especially relevant to browser-based applications using cookie-based authentication.
For a stateless API using bearer tokens in an Authorization header, the CSRF considerations differ and should be evaluated based on the authentication mechanism and browser threat model.
63. What is CORS?
Answer:
CORS stands for Cross-Origin Resource Sharing.
It controls whether a browser allows JavaScript from one origin to access resources on another origin.
For example:
frontend.example.com
↓
api.example.com
requires appropriate CORS configuration.
64. What is method-level security?
Answer:
It allows authorization rules directly on methods.
For example:
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
}
Enable it with:
Java
@EnableMethodSecurity
65. What is the difference between roles and authorities?
Answer:
Authorities are general permissions.
Roles are commonly represented as authorities with the ROLE_ prefix.
For example:
ROLE_ADMIN
USER_READ
USER_WRITE
A role represents a broader security classification, while authorities can represent granular permissions.
8. Spring Boot Testing
66. How do you test Spring Boot applications?
Answer:
Common approaches include:
- JUnit 5
- Mockito
@SpringBootTest@WebMvcTest@DataJpaTest- Testcontainers
- MockMvc
67. What is @SpringBootTest?
Answer:
It loads a Spring application context for integration-style testing.
@SpringBootTest
class UserServiceTest {
}
It is useful when multiple Spring components need to work together.
68. What is @WebMvcTest?
Answer:
It focuses on Spring MVC components, typically controllers.
@WebMvcTest(UserController.class)
class UserControllerTest {
}
It is lighter than loading the entire application context.
69. What is @DataJpaTest?
Answer:
It focuses on JPA components.
It is useful for testing:
- Repositories
- Entity mappings
- JPA queries
70. What is Mockito?
Answer:
Mockito is a mocking framework used for unit testing.
Example:
@Mock
private UserRepository repository;
@InjectMocks
private UserService service;
You can define behavior:
when(repository.findById(1L))
.thenReturn(Optional.of(user));
71. What is MockMvc?
Answer:
MockMvc allows Spring MVC endpoints to be tested without starting a real HTTP server.
Example:
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());
72. What is Testcontainers?
Answer:
Testcontainers runs real infrastructure in containers during tests.
Examples:
PostgreSQL
MySQL
Kafka
Redis
MongoDB
This can provide more realistic integration testing than mocking the database.
73. What is the difference between unit and integration testing?
Answer:
Unit test:
Tests one component in isolation.
Service → mocked repository
Integration test:
Tests multiple components together.
Controller
↓
Service
↓
Repository
↓
Database
9. Microservices
74. Why is Spring Boot popular for microservices?
Answer:
Spring Boot provides:
- Embedded servers
- REST APIs
- Dependency injection
- Configuration
- Actuator
- Security
- Database integration
- Cloud integrations
- Observability support
This makes it well suited for independently deployable services.
75. What is Spring Cloud?
Answer:
Spring Cloud provides tools and abstractions for distributed systems and cloud-native applications.
Depending on the project, it can support concerns such as:
- Service-to-service communication
- Configuration
- Resilience
- Gateway routing
- Distributed tracing integration
76. What is service discovery?
Answer:
Service discovery allows services to dynamically locate other services.
Instead of:
http://10.0.0.25:8080
a service can discover another service through a registry or platform mechanism.
Examples historically include:
Eureka
Consul
Kubernetes Service Discovery
77. What is an API Gateway?
Answer:
An API Gateway provides a single entry point for clients.
It can handle:
- Routing
- Authentication
- Authorization
- Rate limiting
- Logging
- Request transformation
- Load balancing
Examples include Spring Cloud Gateway and cloud-native API gateways.
78. What is circuit breaker?
Answer:
A circuit breaker prevents repeated calls to an unhealthy downstream service.
Typical states:
CLOSED
↓ failures
OPEN
↓ timeout
HALF_OPEN
↓ success
CLOSED
Resilience4j is commonly used with Spring Boot.
79. What is retry?
Answer:
Retry automatically attempts a failed operation again.
For example:
Request
↓
Failure
↓
Retry
↓
Failure
↓
Retry
Retries should be used carefully because they can amplify load.
Avoid retrying non-idempotent operations blindly.
80. What is idempotency?
Answer:
An operation is idempotent if performing it multiple times has the same intended effect as performing it once.
For example:
PUT /users/123
can be designed to be idempotent.
For payment APIs, idempotency keys are commonly used to prevent duplicate charges.
10. Messaging and Event-Driven Architecture
81. How does Spring Boot integrate with Kafka?
Answer:
Spring Boot provides Kafka integration through Spring Kafka.
A consumer can be defined using:
@KafkaListener(
topics = "orders",
groupId = "order-service"
)
public void consume(OrderEvent event) {
}
82. What is @KafkaListener?
Answer:
It marks a method as a Kafka message listener.
Spring manages:
- Consumer lifecycle
- Polling
- Deserialization
- Listener invocation
- Error handling
83. What is the difference between synchronous and asynchronous communication?
Answer:
Synchronous:
Service A
↓ request
Service B
↓ response
Service A
Asynchronous:
Service A
↓ event
Kafka
↓
Service B
Asynchronous communication can improve decoupling and resilience.
84. When should you use Kafka instead of REST?
Answer:
REST is usually appropriate for:
- Request/response operations
- Queries
- Immediate results
Kafka is appropriate for:
- Events
- Asynchronous processing
- High-throughput pipelines
- Event-driven architectures
- Decoupling services
85. What is the Outbox Pattern?
Answer:
The Outbox Pattern solves the problem of atomically updating a database and publishing an event.
Instead of:
DB transaction
+
Kafka publish
the application writes the business data and an outbox event in the same database transaction.
A separate process then publishes the outbox event to Kafka.
This reduces the risk of database state and event state becoming inconsistent.
11. Actuator and Production
86. What is Spring Boot Actuator?
Answer:
Actuator provides production-oriented endpoints for:
- Health
- Metrics
- Application information
- Environment
- Logging
- Monitoring
Example:
/actuator/health
/actuator/metrics
87. What is a health check?
Answer:
A health check determines whether the application or its dependencies are functioning correctly.
Example:
/actuator/health
In Kubernetes, health information is commonly mapped to:
liveness
readiness
88. What is the difference between liveness and readiness?
Answer:
Liveness:
Should this application instance be restarted?
Readiness:
Can this instance currently receive traffic?
This distinction is important in Kubernetes deployments.
89. What is Micrometer?
Answer:
Micrometer provides a vendor-neutral metrics API.
It allows Spring Boot applications to expose metrics to systems such as:
Prometheus
Grafana
Datadog
New Relic
CloudWatch
90. How do you monitor a Spring Boot application?
Answer:
A production monitoring strategy should typically include:
Logs
Metrics
Traces
Health checks
Alerts
Dashboards
Common technologies include:
Spring Boot Actuator
Micrometer
Prometheus
Grafana
OpenTelemetry
ELK/OpenSearch
Cloud monitoring platforms
12. Advanced Spring Boot
91. What is Spring AOP?
Answer:
Aspect-Oriented Programming separates cross-cutting concerns from business logic.
Examples:
Logging
Security
Transactions
Auditing
Metrics
Example:
@Around("@annotation(Auditable)")
public Object audit(ProceedingJoinPoint joinPoint) {
...
}
92. How does Spring AOP work?
Answer:
Spring AOP commonly uses proxies.
For example:
Client
↓
Spring Proxy
↓
Target Bean
The proxy can execute additional behavior before or after the target method.
93. What is the difference between JDK dynamic proxy and CGLIB?
Answer:
JDK dynamic proxies work through interfaces.
CGLIB-style proxies work by subclassing concrete classes.
Spring can choose the proxy mechanism depending on configuration and the target type.
This is important when understanding:
@Transactional@Cacheable@Async- Security interception
94. What is @Async?
Answer:
@Async allows a method to execute asynchronously using a task executor.
@Async
public CompletableFuture<Void> process() {
...
}
Enable it with:
Java
@EnableAsync
In production, the executor should generally be explicitly configured rather than relying blindly on defaults.
95. What is Spring Cache?
Answer:
Spring Cache provides an abstraction for caching method results.
Example:
@Cacheable("users")
public User findUser(Long id) {
return repository.findById(id).orElseThrow();
}
Possible providers include:
Caffeine
Redis
Hazelcast
Ehcache
96. What is @Cacheable?
Answer:
@Cacheable caches the return value of a method.
Example:
@Cacheable(value = "users", key = "#id")
public User findById(Long id) {
return repository.findById(id).orElseThrow();
}
The next request with the same key can return the cached value instead of executing the method.
97. What changed from Spring Boot 2 to Spring Boot 3?
Answer:
Important changes include:
Java 17 baseline
Spring Boot 3 requires Java 17 or later.
Jakarta namespace
Spring Boot 3 uses:
Java
jakarta.*
instead of:
Java
javax.*
For example:
Java
jakarta.persistence.Entity
rather than:
Java
javax.persistence.Entity
Spring Framework 6
Spring Boot 3 is based on Spring Framework 6.
Observability
Modern Spring Boot has stronger observability integration around metrics and tracing.
98. What is the difference between Spring Boot 3 and Spring Framework 6?
Answer:
They are related but different.
Spring Framework 6:
The underlying application framework.
Spring Boot 3:
The opinionated application platform built on Spring Framework 6.
Conceptually:
Spring Boot 3
↓
Spring Framework 6
↓
Java 17+
99. How would you design a production-ready Spring Boot microservice?
Answer:
A strong answer should cover more than REST endpoints.
I would consider:
API
↓
Controller
↓
Service
↓
Repository
↓
Database
plus:
Security
Validation
Exception handling
Transactions
Caching
Messaging
Observability
Health checks
Configuration
Secrets management
Resilience
Testing
CI/CD
Containerization
For example:
┌──────────────┐
│ API Gateway │
└──────┬───────┘
│
┌──────▼───────┐
│ Spring Boot │
│ Microservice │
└──┬────┬───┬──┘
│ │ │
┌─────▼┐ ┌─▼─┐ ┌▼────────┐
│ DB │ │Kafka│ │ Redis │
└──────┘ └────┘ └─────────┘
│
┌──────▼───────┐
│ Observability│
│ Metrics/Logs │
│ Tracing │
└──────────────┘
The important interview point is that production readiness is a system-level concern, not simply writing a REST controller.
100. How would you improve the performance of a Spring Boot application?
Answer:
I would first measure before optimizing.
I would investigate:
Application
- CPU
- Memory
- Thread pools
- Garbage collection
- Connection pools
Database
- Slow queries
- Missing indexes
- N+1 queries
- Connection pool configuration
- Query plans
API
- Response payload size
- Serialization
- Pagination
- Caching
Distributed systems
- Network latency
- Downstream dependencies
- Retry storms
- Circuit breakers
- Kafka throughput
JVM
- Heap configuration
- GC behavior
- Thread usage
- Allocation rates
Observability
Use:
Spring Boot Actuator
Micrometer
Prometheus
Grafana
OpenTelemetry
APM
JFR
The strongest answer is:
Measure → identify the bottleneck → optimize → load test → measure again.