2. Spring Framework Interview Q&A
Dashboard
60 Master Q&A Set
Home › Spring Framework Interview Q&A

🌱 Spring Framework Technical Interview Questions & Answers

Exhaustive 60-Question Master Guide covering Spring Core, Bean Management, Configuration, AOP, Transactions, Events, and Senior Scenario Questions.

📌 Index of Topics Covered (60 Questions)

SectionCategoryQuestion RangeKey Concepts Included
1. Spring CoreIoC & DI FundamentalsQ1 – Q10What is Spring, IoC, DI, DI Types, Constructor vs Field Injection, Bean Definition, Bean Lifecycle, Scopes
2. Bean ManagementAnnotations & ScanningQ11 – Q20BeanFactory vs ApplicationContext, Component Scanning, Stereotypes, @Component vs @Bean, @Configuration, @Primary, @Qualifier, @Lazy
3. DI & ConfigurationConfiguration & InjectionQ21 – Q30Autowiring Modes, SpEL, @Value, XML vs Java Config, Lifecycle Hooks, Collection Injection, Circular Dependencies, Custom Beans
4. Spring AOPAspect-Oriented ProgrammingQ31 – Q40AOP Concepts, Cross-Cutting Concerns, Terminology (Aspect, Advice, Join Point, Pointcut), Advice Types, Spring AOP vs AspectJ, JDK vs CGLIB Proxies
5. Transactions & AdvancedTransactions & EventsQ41 – Q50@Transactional, Propagation, Isolation Levels, Exception Rollbacks, Declarative vs Programmatic, Spring Events, Singleton Concurrency
6. Senior ScenariosArchitectural & DebuggingQ51 – Q60Debugging Injection, Ambiguous Beans, Circular Dependency Fixes, Proxy Self-Invocation, Mutable State Fixes, AOP Logging, Startup Profiling

1. Spring Core (Q1 – Q10)

Q1: What is the Spring Framework?
Answer: Spring is an open-source, lightweight, enterprise Java application framework designed to simplify enterprise application development. It provides an Inversion of Control (IoC) container, Dependency Injection (DI), Aspect-Oriented Programming (AOP), transaction management, and modular integrations.
Q2: What are the advantages of using Spring?
Answer:
  • Loose Coupling: Dependency Injection removes hardcoded class dependencies.
  • Lightweight Container: Efficient memory footprint and lifecycle management.
  • AOP Support: Modularizes cross-cutting concerns like security, logging, and transactions.
  • Boilerplate Reduction: Eliminates boilerplate database code via Spring Data JPA and JdbcTemplate.
  • Ecosystem Integration: Seamlessly integrates with Spring Boot, Spring Security, and Cloud.
Q3: What is Inversion of Control (IoC)?
Answer: IoC is an architectural design principle where control over object creation, dependency resolution, and lifecycle management is inverted from the developer code to an external container (the Spring IoC Container).
Q4: What is Dependency Injection (DI)?
Answer: DI is a concrete pattern implementing IoC. Instead of an object instantiating its own dependencies using new, the Spring container creates and supplies required dependent objects automatically at runtime.
Q5: What are the different types of Dependency Injection?
Answer:
  • Constructor Injection: Dependencies are supplied through target class constructor parameters.
  • Setter Injection: Dependencies are supplied via JavaBean setter methods.
  • Field Injection: Dependencies are injected directly into private fields via reflection using @Autowired.
Q6: Why is Constructor Injection preferred over Field Injection?
Answer: 1. Immutability: Allows declaring dependencies as final.
2. Testability: Enables instantiating beans in unit tests by passing mocks into constructor without needing Spring test framework.
3. Null Safety: Guarantees that an initialized object has all required dependencies non-null.
4. Circular Dependency Detection: Triggers immediate compile/startup failures if circular dependencies exist.
Q7: What is a Spring Bean?
Answer: A Spring Bean is an object that is instantiated, configured, assembled, and managed by the Spring IoC container throughout its application lifecycle.
Q8: What is the lifecycle of a Spring Bean?
Answer: 1. Instantiation (Constructor invocation)
2. Populate Properties (Dependency Injection)
3. Aware Interfaces (BeanNameAware, BeanFactoryAware, ApplicationContextAware)
4. BeanPostProcessor.postProcessBeforeInitialization()
5. @PostConstruct / InitializingBean.afterPropertiesSet() / Custom init-method
6. BeanPostProcessor.postProcessAfterInitialization()
7. Bean Ready for Use
8. @PreDestroy / DisposableBean.destroy() / Custom destroy-method
Q9: What are the different Bean Scopes in Spring?
Answer:
  • singleton (Default): One single shared instance per Spring IoC container.
  • prototype: A new bean instance is created every time it is requested from the container.
  • request: One instance per HTTP request (Web context).
  • session: One instance per HTTP session.
  • application: One instance per ServletContext.
  • websocket: One instance per WebSocket lifecycle.
Q10: What is the difference between Singleton and Prototype scope?
Answer:
  • Singleton: Created once at container startup (eager loading), shared across all callers, Spring manages complete lifecycle including destruction.
  • Prototype: Created on-demand when requested, every caller gets a unique instance, Spring does NOT execute destruction lifecycle hooks.

2. Spring Bean Management (Q11 – Q20)

Q11: What is the difference between BeanFactory and ApplicationContext?
Answer:
  • BeanFactory: Basic IoC container interface. Uses lazy loading (instantiates beans only when requested via getBean()). Lightweight for memory-constrained devices.
  • ApplicationContext: Advanced enterprise container interface extending BeanFactory. Supports eager loading of singletons, AOP integration, internationalization (MessageSource), event publication, and Web ApplicationContext.
Q12: What is Component Scanning?
Answer: Component scanning is the automated mechanism by which Spring inspects the classpath for annotated classes and registers them as Spring Beans in the ApplicationContext.
Q13: What is the purpose of `@ComponentScan`?
Answer: Configures package scanning directives for Spring. @ComponentScan(basePackages = "com.example") instructs Spring to scan specified packages and sub-packages for stereotype annotations.
Q14: What is the difference between `@Component`, `@Service`, `@Repository`, and `@Controller`?
Answer: - @Component: Generic stereotype for any Spring-managed component.
- @Service: Specializes @Component for the business service layer.
- @Repository: Specializes @Component for data access (DAO). Automatically translates database exceptions into Spring's DataAccessException hierarchy.
- @Controller: Specializes @Component for Spring MVC presentation controllers.
Q15: What is the difference between `@Component` and `@Bean`?
Answer:
  • @Component: Class-level annotation. Used when you own the class source code and want Spring to auto-detect it via component scanning.
  • @Bean: Method-level annotation inside @Configuration classes. Used when instantiating third-party library classes or requiring custom factory logic.
Q16: What is the purpose of the `@Configuration` annotation?
Answer: Marks a class as a source of Spring Bean definitions. CGLIB proxies enhance @Configuration classes so that calling @Bean methods internally returns the cached container singleton instance rather than creating duplicate objects.
Q17: What is `@Primary`?
Answer: Annotates a bean to give it primary precedence when multiple beans of the same type exist, resolving autowiring ambiguity by default.
Q18: What is `@Qualifier`?
Answer: Used at the injection site (e.g. @Qualifier("beanName")) to explicitly specify which exact bean candidate to inject, overriding @Primary.
Q19: How does Spring resolve multiple beans of the same type?
Answer: 1. Checks for @Qualifier("specificName") at injection point.
2. Checks for a bean marked with @Primary.
3. Matches injection variable field/parameter name with the Bean name.
4. If ambiguity remains, throws NoUniqueBeanDefinitionException.
Q20: What is Lazy Initialization (`@Lazy`)?
Answer: Defers bean instantiation and initialization until the bean is explicitly requested for the first time, rather than creating it eagerly during container startup.

3. Dependency Injection & Configuration (Q21 – Q30)

Q21: What is Autowiring?
Answer: Autowiring is Spring's capability to resolve and inject collaborating bean dependencies automatically into matching bean properties.
Q22: What are the different modes of Autowiring?
Answer:
  • no: Default, no autowiring; ref must be defined explicitly.
  • byName: Autowires by matching property name with bean name.
  • byType: Autowires by matching property data type.
  • constructor: Autowires by matching constructor parameter types.
Q23: What is Spring Expression Language (SpEL)?
Answer: SpEL is an expression language supporting querying and manipulating object graphs at runtime (e.g. #{systemProperties['user.region']} or #{bean.property > 100}).
Q24: What is the `@Value` annotation?
Answer: Used to inject property values from external configuration files (@Value("${app.timeout:5000}")) or SpEL expression evaluation results into bean fields or parameters.
Q25: What is the difference between XML configuration and Java-based configuration?
Answer:
  • XML Config: Externalized XML file (), verbose, no compile-time type checking.
  • Java-based Config: Type-safe @Configuration classes with @Bean methods, refactoring-friendly, compile-time validation.
Q26: What are `@PostConstruct` and `@PreDestroy`?
Answer: JSR-250 lifecycle annotations:
- @PostConstruct: Method executed immediately after dependency injection completes to perform initialization logic.
- @PreDestroy: Method executed right before the container destroys the bean to release resources.
Q27: How do you inject collections in Spring?
Answer: Spring automatically autowires all beans matching the element type into a List<PaymentStrategy>, Set<Filter>, or Map<String, Service> (where map key is bean name).
Q28: What is circular dependency, and how does Spring handle it?
Answer: Occurs when Class A depends on Class B, and Class B depends on Class A.
- Spring handles circular dependencies automatically for Setter/Field injection using three-level caches.
- For Constructor injection, Spring fails at startup with BeanCurrentlyInCreationException. Fix using @Lazy on one constructor parameter or refactoring into a shared service.
Q29: Why is Field Injection discouraged?
Answer: Hides dependencies, violates immutability (cannot use final), prevents easy unit testing without reflection/Spring container, and hides circular dependency warnings.
Q30: How do you create a custom Bean?
Answer: Either annotate a class with @Component (for auto-scanning) or declare a method annotated with @Bean inside a @Configuration class.

4. Spring AOP (Q31 – Q40)

Q31: What is Aspect-Oriented Programming (AOP)?
Answer: AOP is a programming paradigm that complements OOP by isolating cross-cutting concerns from core business logic.
Q32: Why do we use AOP?
Answer: Eliminates code duplication and tight coupling by separating system-wide concerns (logging, security, transaction management) into reusable aspects.
Q33: What are cross-cutting concerns?
Answer: Operational tasks that span across multiple layers of an application (e.g. logging, performance monitoring, security authorization, transaction demarcation).
Q34: Explain Aspect, Advice, Join Point, Pointcut, Target, and Weaving.
Answer:
  • Aspect: Module containing cross-cutting logic.
  • Advice: Action taken by aspect at a join point (code executed).
  • Join Point: Execution point in application (method call).
  • Pointcut: Expression matching target join points (e.g. execution(* com.service..*.*(..))).
  • Target Object: Domain object being advised.
  • Weaving: Linking aspects with target objects (Spring AOP does runtime proxy weaving).
Q35: What are the different types of Advice in Spring AOP?
Answer: - @Before: Executes before method execution.
- @AfterReturning: Executes after method completes normally.
- @AfterThrowing: Executes after method throws exception.
- @After: Executes after method completes (finally).
- @Around: Wraps method, controls execution proceed(), arguments, and return values.
Q36: What is the difference between Spring AOP and AspectJ?
Answer:
  • Spring AOP: Pure Java, proxy-based, supports method execution join points only, runtime weaving.
  • AspectJ: Full AOP framework, bytecode modification, supports field access & constructor join points, compile-time/load-time weaving.
Q37: How does Spring AOP create proxies?
Answer: Wraps target objects in proxy instances at runtime that intercept calls, execute advice, and delegate to target methods.
Q38: What is the difference between JDK Dynamic Proxy and CGLIB Proxy?
Answer:
  • JDK Dynamic Proxy: Used when target implements at least one interface.
  • CGLIB Proxy: Generates a subclass of target when no interfaces are implemented (Default in Spring Boot 2.x+).
Q39: Why can't Spring AOP intercept private methods?
Answer: Proxies wrap target objects. Internal calls or private methods bypass proxy delegation, executing directly on target instance.
Q40: What are practical use cases of AOP?
Answer: Transaction management (@Transactional), performance monitoring, audit logging, rate limiting, and security authorization.

5. Transactions & Advanced Spring (Q41 – Q50)

Q41: What is Transaction Management in Spring?
Answer: Provides unified abstraction for managing database transactions consistently across JDBC, JPA, and Hibernate.
Q42: What is the `@Transactional` annotation?
Answer: Declarative annotation that wraps method execution inside a database transaction managed by Spring's PlatformTransactionManager.
Q43: What are the different transaction propagation levels?
Answer:
  • REQUIRED (Default): Join existing or create new transaction.
  • REQUIRES_NEW: Always suspend existing and start brand new transaction.
  • MANDATORY: Must run in existing transaction; throws error if none.
  • SUPPORTS: Runs in transaction if exists; non-transactional otherwise.
  • NOT_SUPPORTED: Suspends existing transaction and runs non-transactionally.
  • NEVER: Throws exception if active transaction exists.
  • NESTED: Executes in nested savepoint if transaction active.
Q44: What are transaction isolation levels?
Answer: Controls data visibility across concurrent transactions: DEFAULT, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE.
Q45: Difference between checked and unchecked exceptions in transaction rollback?
Answer: By default, transactions roll back ONLY on Unchecked Exceptions (RuntimeException/Error). They do NOT roll back on Checked Exceptions unless specified via @Transactional(rollbackFor = Exception.class).
Q46: Programmatic vs Declarative Transaction Management?
Answer:
  • Declarative: Uses @Transactional annotation (clean, metadata-driven).
  • Programmatic: Uses TransactionTemplate or PlatformTransactionManager explicitly in code (fine-grained control).
Q47: What are Spring Events, and how do they work?
Answer: Decoupled event publishing mechanism inside ApplicationContext using publishEvent() and @EventListener.
Q48: What is the `ApplicationEventPublisher`?
Answer: Interface used to publish application events to registered listeners.
Q49: How does Spring manage singleton beans in a multi-threaded environment?
Answer: Singleton beans are shared across threads; they MUST be **stateless** (no mutable instance variables).
Q50: What are the best practices for designing Spring applications?
Answer: Prefer constructor injection, keep singletons stateless, use interface-driven design, leverage proper transaction propagation, and isolate cross-cutting concerns using AOP.

6. Senior Scenario-Based Interview Questions (Q51 – Q60)

Q51: Scenario: A Spring bean is not getting injected. How would you debug it?
Answer: 1. Verify stereotype annotation on target class.
2. Check @ComponentScan base packages.
3. Inspect startup logs for NoSuchBeanDefinitionException.
4. Resolve multiple bean conflicts using @Qualifier.
Q52: Scenario: Two beans of the same type exist. How will Spring decide which one to inject?
Answer: 1. Checks for @Qualifier("name").
2. Checks for @Primary bean.
3. Matches variable name with bean name.
4. Throws NoUniqueBeanDefinitionException if unresolved.
Q53: Scenario: Your application fails due to a circular dependency. How would you fix it?
Answer: Refactor into a 3rd service, or annotate a constructor parameter with @Lazy, or convert to setter injection.
Q54: Scenario: Explain the complete lifecycle of a Spring Bean from creation to destruction.
Answer: Constructor → DI → Aware callbacks → postProcessBeforeInitialization@PostConstructpostProcessAfterInitialization → Active Bean → @PreDestroy.
Q55: Scenario: How does Spring manage transactions across multiple service methods?
Answer: Uses TransactionSynchronizationManager to bind database connection to current thread threadlocal across service boundaries.
Q56: Scenario: How would you implement logging across all service methods without modifying business code?
Answer: Create an @Aspect class with an @Around("execution(* com.service..*.*(..))") advice logging execution time and parameters.
Q57: Scenario: A singleton bean stores mutable state and multiple users access it concurrently. What problems occur, and how to fix?
Answer: Data corruption & race conditions occur. Fix: Make bean stateless, use method-local variables, or use ConcurrentHashMap / ThreadLocal.
Q58: Scenario: How would you profile and optimize the startup time of a Spring application?
Answer: Enable Spring Boot startup tracking (BufferingApplicationStartup), use @Lazy on non-critical beans, and restrict component scan packages.
Q59: Scenario: Explain how proxy-based AOP works internally.
Answer: Target object is wrapped in a CGLIB subclass / JDK dynamic proxy. Method calls invoke proxy advice chain first before delegating to target method.
Q60: Scenario: How do you make Spring applications more testable and maintainable?
Answer: Use constructor injection for easy mock passing in unit tests, decouple interfaces from implementations, and avoid static method calls.