What is the difference between Spring Boot and the traditional Spring Framework? How does Spring Boot simplify application development?
Spring Framework:
* Requires manual configuration (XML or Java-based).
* Developers must set up dependencies, servers, and project structure.
Spring Boot:
* Provides auto-configuration and embedded servers.
* Uses “starter” dependencies for common features.
* Minimal setup—just run the main class to start the app.
* Simplifies development by reducing boilerplate and configuration.
Can you imagine a case when you would not recommend using Spring (Boot)? What would you use instead and why?
Not recommended:
* For very simple or lightweight applications (e.g., small REST APIs, CLI tools) where Spring’s features are overkill.
* When fast startup and low memory usage are critical (e.g., serverless, microservices with strict resource limits).
Alternatives:
* Micronaut, Quarkus: Lightweight Java frameworks with faster startup and lower memory footprint.
* Plain Java with JAX-RS (Jersey), or frameworks like Spark Java: For minimalistic REST APIs.
What does the @PostConstruct annotation do in Spring Boot?
Marks a method to run after the bean’s dependencies are injected and initialization is complete.
Used for initialization logic (e.g., setting up resources) after the bean is created.
What are starter dependencies in Spring Boot?
Predefined dependency packages that bundle commonly used libraries and configurations for specific tasks (e.g., web, data, security).
Simplify setup—just add a starter (like spring-boot-starter-web) and get all required dependencies automatically.
What is the Spring Boot actuator?
A module that provides production-ready features for monitoring and managing applications.
Exposes endpoints for health checks, metrics, environment info, and more.
What are the main features of Spring?
Dependency Injection (DI): Manages object dependencies.
Aspect-Oriented Programming (AOP): Separates cross-cutting concerns (e.g., logging, security).
Data Access: Simplifies database operations (JDBC, ORM).
Transaction Management: Handles transactions across resources.
Model-View-Controller (MVC): Supports web application development.
Integration: Connects with other frameworks and technologies.
How is Dependency Injection useful for writing maintainable code?
Promotes loose coupling—classes depend on abstractions, not concrete implementations.
Makes code easier to test (can inject mocks/stubs).
Simplifies code changes and refactoring.
Improves reusability and flexibility.
What is a Spring Bean? Which bean scopes do you know?
Spring Bean: An object managed by the Spring container (created, configured, and wired automatically).
Bean scopes:
* Singleton (default): One instance per Spring container.
* Prototype: New instance each time requested.
* Request: One per HTTP request (web apps).
* Session: One per HTTP session (web apps).
* Application: One per ServletContext (web apps).
* Websocket: One per WebSocket session.
What is the DispatcherServlet?
The central front controller in Spring MVC.
Receives all HTTP requests, dispatches them to appropriate controllers, and returns responses.
Handles request routing, view resolution, and exception handling.
How does Spring Boot’s auto-configuration work, and what role does @EnableAutoConfiguration play?
Auto-configuration:
* Automatically configures beans and settings based on classpath contents and project properties.
* Reduces manual setup—just add dependencies, and Spring Boot configures them for you.
@EnableAutoConfiguration:
* Annotation that triggers auto-configuration.
* Usually included via @SpringBootApplication.
What are the central parts of Spring MVC?
DispatcherServlet: Front controller that routes requests.
Controller: Handles requests and returns responses or views.
Model: Holds data to be displayed or processed.
View: Renders the output (e.g., HTML, JSON).
ViewResolver: Maps view names to actual view implementations.
What is an interceptor and how is it different from a filter?
Interceptor:
* Works at the Spring MVC level (inside DispatcherServlet).
* Used for pre- and post-processing of controller requests (e.g., logging, authentication).
* Can access and modify request/response and handler objects.
Filter:
* Works at the Servlet level (before DispatcherServlet).
* Used for generic request/response processing (e.g., encoding, security).
* Cannot access Spring-specific objects like controllers.
Can you explain the lifecycle of a Spring bean?
What are the lifecycle hooks of a Spring bean?
Initialization hooks:
* @PostConstruct annotated method
* InitializingBean.afterPropertiesSet()
* Custom init method (specified in bean config)
Destruction hooks:
* @PreDestroy annotated method
* DisposableBean.destroy()
* Custom destroy method (specified in bean config)
How can BeanPostProcessor be used to enhance the functionality of a bean?
Allows custom logic before and after bean initialization.
Can modify, wrap, or replace beans (e.g., add proxies, inject extra behavior).
Used for features like AOP, custom annotations, or validation.
How is the @Transactional annotation implemented in Spring Core? Can a private method be annotated with @Transactional, and will it work as expected? What happens when a @Transactional method is called from another @Transactional method within the same class?
Implementation:
Uses proxies (AOP) to manage transactions around public methods.
Private methods:
Annotation won’t work as expected—proxies only intercept public methods.
Internal calls:
Calling a @Transactional method from another method in the same class bypasses the proxy, so transaction management won’t be applied.
What proxy types exist in Spring, and what are the differences?
JDK Dynamic Proxy:
* Used when the bean implements at least one interface.
* Proxy implements the same interfaces as the target bean.
CGLIB Proxy:
* Used when the bean does not implement any interfaces.
* Proxy subclasses the target class (creates a subclass at runtime).
Difference:
* JDK proxy works with interfaces; CGLIB works with concrete classes.
* CGLIB cannot proxy final classes or methods.
What is Inversion of Control (IoC), and how does Spring manage dependencies?
Inversion of Control (IoC):
Design principle where control of object creation and dependency management is transferred from the application code to a container.
Spring’s approach:
Spring IoC container creates, configures, and injects dependencies into beans automatically (using XML, annotations, or Java config).
What are the differences between @Autowired, @Inject, and @Resource annotations?
@Autowired:
* Spring-specific; injects dependencies by type (default).
* Can be used on constructors, fields, or setters.
@Inject:
* From JSR-330 (Java standard); functionally similar to @Autowired.
* Injects by type.
@Resource:
* From JSR-250; injects by name (default), then by type if name not found.
* Can specify the bean name with the name attribute.
What are the different types of Dependency Injection in Spring? When should each be used? Why is field injection not recommended?
Constructor Injection: Dependencies provided via constructor.
* Recommended: Ensures immutability, makes dependencies explicit, supports testing.
Setter Injection: Dependencies set via setter methods.
* Use when: Dependencies are optional or can change after object creation.
Field Injection: Dependencies injected directly into fields.
* Not recommended: Hides dependencies, makes testing and refactoring harder, breaks immutability.
Can you explain the difference between@Component,@Service,@Repository, and@Controller? When would you use each, and how does Spring manage these beans?
@Component:
* Generic stereotype for any Spring-managed bean.
* Use for general-purpose beans.
@Service:
* Specialization of @Component for service-layer beans.
* Use for business logic/services.
@Repository:
* Specialization of @Component for data access objects (DAOs).
* Adds exception translation for persistence errors.
@Controller:
* Specialization of @Component for web controllers in Spring MVC.
* Handles HTTP requests and responses.
Spring management:
All are detected via component scanning and registered as beans in the application context.
How would you handle circular dependencies in Spring? What strategies can resolve this, and what are the implications?
Circular dependency: When two or more beans depend on each other, causing a loop.
Strategies to resolve:
* Constructor injection: Not supported for circular dependencies—Spring will throw an error.
* Setter or field injection: Spring can resolve circular dependencies by injecting proxies or partially constructed beans.
* Refactor design: Break the dependency loop by introducing a third bean, using interfaces, or redesigning the relationships.
* Use @Lazy: Delays bean initialization to break the cycle.
Implications:
* Circular dependencies can make code harder to maintain and test.
* Prefer refactoring to avoid them when possible.
How does Spring handle incoming HTTP requests?
DispatcherServlet receives all HTTP requests as the front controller.
HandlerMapping determines which controller should handle the request.
Controller processes the request and returns a response or view name.
ViewResolver maps the view name to an actual view (e.g., HTML, JSON).
Response is rendered and sent back to the client.
What are the pros and cons of using Spring Boot?
Pros:
* Rapid development with minimal configuration.
* Embedded servers (no need for external deployment).
* Auto-configuration and starter dependencies simplify setup.
* Production-ready features (Actuator, metrics, health checks).
Cons:
* Less control over fine-grained configuration.
* Larger application size and memory footprint.
* May include unnecessary dependencies if not managed carefully.