Chapter 3 - Spring & Spring Boot
Chapter 3 – Spring & Spring Boot (Questions 26–40)
This chapter focuses on advanced Spring topics commonly asked in Senior and Staff Backend Engineer interviews.
Question 26
What is Dependency Injection (DI), and why is it important?
Why They Ask
Dependency Injection is the core concept behind Spring. Interviewers want to know whether you understand how Spring manages object creation and dependencies.
Model Answer
Dependency Injection (DI) is a design pattern where the Spring container creates and injects dependencies into objects instead of the objects creating them manually.
Without DI:
public class PaymentService {
private PaymentRepository repository =
new PaymentRepository();
}
With DI:
@Service
public class PaymentService {
private final PaymentRepository repository;
public PaymentService(PaymentRepository repository) {
this.repository = repository;
}
}
Benefits:
- Loose coupling
- Easier testing
- Better maintainability
- Easier replacement of implementations
- Spring manages the object lifecycle
Follow-up
Why is constructor injection preferred over field injection?
Answer
Constructor injection:
- Makes dependencies explicit
- Supports immutable fields
- Easier unit testing
- Prevents partially initialized objects
Spring officially recommends constructor injection.
Question 27
Explain the Spring Bean Lifecycle.
Model Answer
A Spring Bean goes through several phases:
Instantiate Bean
↓
Inject Dependencies
↓
@PostConstruct
↓
Bean Ready
↓
Application Running
↓
@PreDestroy
↓
Bean Destroyed
Example:
@Component
public class CacheService {
@PostConstruct
public void init() {
System.out.println("Initializing cache...");
}
@PreDestroy
public void destroy() {
System.out.println("Cleaning resources...");
}
}
Interview Tip
Mention that Spring manages singleton beans by default.
Question 28
What are the different Bean Scopes in Spring?
Model Answer
| Scope | Description |
|---|---|
| Singleton | One instance per Spring container |
| Prototype | New object every request |
| Request | One per HTTP request |
| Session | One per HTTP session |
| Application | Shared across the web application |
| WebSocket | One per WebSocket |
Example:
@Scope("prototype")
@Component
public class ReportGenerator {
}
Follow-up
Which scope do you use most?
Answer:
Almost always Singleton for stateless services.
Question 29
Explain Spring Boot Auto-Configuration.
Model Answer
Spring Boot automatically configures beans based on:
- Classpath
- Dependencies
- Configuration properties
Example:
Add this dependency:
spring-boot-starter-data-jpa
Spring automatically creates:
- DataSource
- EntityManager
- TransactionManager
- Repository beans
No manual XML configuration is needed.
Advantages
- Less boilerplate
- Faster development
- Opinionated defaults
- Easy customization
Question 30
What is the difference between @Component, @Service, @Repository, and @Controller?
Model Answer
All are specialized forms of @Component.
| Annotation | Purpose |
|---|---|
| @Component | Generic Spring Bean |
| @Service | Business logic |
| @Repository | Database layer |
| @Controller | MVC Controller |
| @RestController | REST API Controller |
Example:
@Service
public class UserService {
}
@Repository
public class UserRepository {
}
@Repository also enables automatic exception translation into Spring's DataAccessException hierarchy.
Question 31
Explain Spring MVC Request Flow.
Model Answer
Request flow:
Client
↓
DispatcherServlet
↓
Controller
↓
Service
↓
Repository
↓
Database
↓
Response
Example:
@GetMapping("/users/{id}")
public UserDto findUser(
@PathVariable Long id) {
return userService.find(id);
}
The DispatcherServlet is the front controller that routes all incoming requests.
Follow-up
Why is DispatcherServlet called the Front Controller?
Because it handles every request before forwarding it to the correct controller.
Question 32
Explain Spring Boot Starter Dependencies.
Model Answer
Starters provide curated dependency sets.
Examples:
spring-boot-starter-web
spring-boot-starter-data-jpa
spring-boot-starter-security
spring-boot-starter-test
Benefits:
- No dependency version conflicts
- Easier upgrades
- Consistent dependency management
Question 33
How does Spring Boot handle configuration?
Model Answer
Spring Boot supports multiple configuration sources:
- application.properties
- application.yml
- Environment variables
- JVM parameters
- Command-line arguments
- External configuration files
Example:
server:
port: 8080
spring:
datasource:
url: jdbc:postgresql://localhost/demo
Configuration can be bound to Java objects:
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
}
Best Practice
Prefer @ConfigurationProperties over repeated @Value annotations for structured configuration.
Question 34
Explain Spring Profiles.
Model Answer
Profiles allow different configurations for different environments.
Example:
application-dev.yml
application-test.yml
application-prod.yml
Activate:
-Dspring.profiles.active=prod
Or:
spring:
profiles:
active: prod
Use Cases
- Different databases
- Logging configuration
- External service endpoints
- Feature flags
Question 35
Explain Spring Data JPA.
Model Answer
Spring Data JPA reduces boilerplate for database access.
Repository:
public interface UserRepository
extends JpaRepository<User, Long> {
}
Spring automatically generates CRUD operations.
Example:
repository.findAll();
repository.findById(id);
repository.save(user);
repository.delete(user);
Custom Query
List<User> findByEmail(String email);
Spring generates SQL automatically.
Follow-up
How does Spring generate these methods?
Answer:
Using proxy implementations created at runtime based on method names.
Question 36
Explain Transaction Management in Spring.
Model Answer
Spring uses @Transactional to manage database transactions.
Example:
@Transactional
public void createOrder() {
orderRepository.save(order);
paymentRepository.save(payment);
}
If any operation fails:
Everything is rolled back.
Transaction Properties
- Propagation
- Isolation
- Timeout
- Read-only
Common Propagation Modes
- REQUIRED
- REQUIRES_NEW
- SUPPORTS
- MANDATORY
Follow-up
What happens if a checked exception is thrown?
By default, Spring rolls back only on unchecked (RuntimeException) exceptions. For checked exceptions, specify:
@Transactional(rollbackFor = Exception.class)
Question 37
What is Lazy Loading vs Eager Loading?
Model Answer
Lazy Loading:
Related entities are loaded only when accessed.
@OneToMany(fetch = FetchType.LAZY)
Eager Loading:
Everything is loaded immediately.
@OneToMany(fetch = FetchType.EAGER)
Best Practice
Prefer Lazy Loading to avoid unnecessary database queries.
Follow-up
What problem can Lazy Loading cause?
LazyInitializationException if accessed outside the persistence context.
Question 38
What is the N+1 Query Problem?
Model Answer
Suppose:
List<Order> orders =
repository.findAll();
Each order loads customer data lazily.
1 query for orders
+
100 queries for customers
=
101 queries
This is the N+1 problem.
Solutions
- JOIN FETCH
- EntityGraph
- DTO projection
- Batch fetching
Example:
@Query("""
SELECT o
FROM Order o
JOIN FETCH o.customer
""")
Question 39
How do you secure a Spring Boot REST API?
Model Answer
Typical security layers include:
- Spring Security
- JWT authentication
- OAuth2/OpenID Connect
- HTTPS
- Role-based authorization
- Input validation
- Rate limiting
- Audit logging
Example:
@EnableWebSecurity
public class SecurityConfig {
}
JWT Flow:
Client
↓
Login
↓
JWT Token
↓
REST Requests
↓
Authentication Filter
↓
Controller
Best Practices
- Never store passwords in plain text.
- Use
BCryptPasswordEncoder. - Validate JWT expiration.
- Apply least-privilege authorization.
Question 40
How would you improve the performance of a Spring Boot application?
Model Answer
Performance tuning should begin with measurement using tools such as Micrometer, Prometheus, Grafana, Java Flight Recorder, or VisualVM.
Key optimization strategies include:
Database Optimization
- Proper indexing
- Optimized SQL
- Pagination
- Avoiding N+1 queries
Caching
Use Redis or in-memory caching for frequently accessed data.
@Cacheable("users")
public User find(Long id) {
...
}
Connection Pooling
Configure HikariCP appropriately:
spring:
datasource:
hikari:
maximum-pool-size: 20
Asynchronous Processing
Use @Async, messaging systems, or CompletableFuture for long-running tasks.
Reduce Serialization Overhead
Return lightweight DTOs instead of entire entity graphs.
Monitor Production
Track:
- Response times
- Error rates
- CPU usage
- Memory consumption
- Database performance
- JVM metrics
Example from Your Experience
At Hubject, I worked on maintaining more than 50 AWS-hosted microservices. Performance improvements involved optimizing service interactions, improving deployment pipelines, monitoring production systems, and ensuring scalability under enterprise workloads. These experiences reinforced the importance of observability and incremental optimization rather than premature tuning.
Common Follow-up Questions
Expect interviewers to explore these related topics:
- What is the difference between Spring and Spring Boot?
- How does Spring Boot auto-configuration work internally?
- Explain
@Primaryand@Qualifier. - What is
BeanFactoryvsApplicationContext? - What is Aspect-Oriented Programming (AOP), and where have you used it?
- How do Spring proxies work (JDK Dynamic Proxy vs CGLIB)?
- What is the difference between
@ControllerAdviceand@ExceptionHandler? - How do you implement centralized exception handling?
- How do you write integration tests with
@SpringBootTest? - When would you use
WebMvcTestinstead ofSpringBootTest? - How do you manage secrets in Spring Boot applications?
- How do you implement health checks and readiness probes for Kubernetes?
Chapter Summary
After mastering this chapter, you should be comfortable discussing:
- Dependency Injection and Inversion of Control
- Bean lifecycle and scopes
- Spring Boot auto-configuration
- Spring MVC architecture
- Configuration and profiles
- Spring Data JPA
- Transaction management
- Lazy vs. eager loading
- N+1 query optimization
- REST API security with Spring Security
- Spring Boot performance tuning
These topics form the foundation of most Senior and Staff Backend Engineer interviews using the Spring ecosystem. The next chapter will build on them with Microservices Architecture, including service decomposition, communication patterns, resilience, observability, distributed transactions, and scalability.