Advanced Spring Interview Questions: Bean Lifecycle, AOP, Transactions, ApplicationContext vs BeanFactory, Type Conversion
This article compiles twelve advanced Spring interview questions covering bean initialization and lifecycle, AOP implementation, transaction management, the differences between ApplicationContext and BeanFactory, type conversion mechanisms, dependency injection, circular dependency resolution with three‑level caches, the event system, @Transactional and @Async annotations, and the inner workings of DispatcherServlet.
1. How does the Spring container initialize a Bean? Describe the Bean lifecycle.
Key points :
Instantiation : Spring creates the Bean instance via its constructor or factory method.
Property population : Spring injects properties and dependencies into the Bean.
BeanNameAware : If the Bean implements setBeanName, Spring passes the Bean name.
BeanFactoryAware : If the Bean implements setBeanFactory, Spring injects the BeanFactory.
ApplicationContextAware : If the Bean implements setApplicationContext, Spring injects the ApplicationContext.
BeanPostProcessor : Spring calls postProcessBeforeInitialization and postProcessAfterInitialization for additional processing.
InitializingBean : If implemented, Spring invokes afterPropertiesSet after property population.
init‑method : A custom init method defined in XML is called after the above steps.
DisposableBean : On container shutdown, Spring calls destroy for cleanup.
destroy‑method : A custom destroy method defined in XML is invoked on shutdown.
2. How is AOP implemented in Spring? Explain the underlying principle.
Key points :
AOP separates cross‑cutting concerns such as logging or transaction management from business logic.
Spring AOP uses dynamic proxies: JDK proxies for Beans that implement interfaces, CGLIB proxies otherwise.
The proxy intercepts method calls and executes additional logic before/after the target method.
Spring defines an Advisor (which holds an Advice) and a Pointcut to specify where the advice applies.
Custom Aspect classes can combine multiple Advice and Pointcut definitions.
3. How does Spring implement transaction management? Explain the mechanism.
Key points :
Spring supports both declarative (annotations or XML) and programmatic transaction management.
Declarative transactions are built on AOP: Spring creates a proxy for the target method and wraps it with transaction logic.
Transaction managers implement PlatformTransactionManager (e.g., JDBC, JPA) to begin, commit, or roll back transactions.
Configuration options include propagation behaviors (e.g., REQUIRED, REQUIRES_NEW), isolation levels, and timeout settings.
4. What is the difference between ApplicationContext and BeanFactory ?
Key points : BeanFactory is the most basic container interface; it provides core configuration and manages singleton Beans only, without support for annotation processing, AOP, or internationalization. ApplicationContext extends BeanFactory and adds enterprise‑level features such as event propagation, resource loading, internationalization, and full AOP support. ApplicationContext pre‑instantiates all singleton Beans at startup, whereas BeanFactory lazily creates Beans on demand.
Because of its richer functionality, ApplicationContext is the recommended way to bootstrap a Spring application.
5. Explain Spring’s type conversion mechanism and how to create a custom converter.
Key points :
Spring uses PropertyEditor and Converter interfaces for type conversion. PropertyEditor converts String values to target types; Converter provides a more generic and flexible conversion API.
Since Spring 3.0, Converter is the preferred approach.
To add a custom conversion, implement Converter, register the implementation as a Bean in the container, and Spring will automatically apply it where needed.
6. How does Spring achieve dependency injection? Describe the internal mechanism.
Key points :
DI allows a Bean’s dependencies to be supplied by the container rather than instantiated directly.
Spring reads configuration (XML, annotations, or Java config) to discover Bean definitions and their dependencies.
During container startup, Beans are instantiated via reflection, and dependencies are injected using constructor, setter, or interface injection. BeanFactory is the core interface for obtaining Beans; ApplicationContext extends it with additional features.
7. How does Spring resolve circular dependencies?
Key points :
Circular dependencies occur when two or more singleton Beans depend on each other.
Spring uses a three‑level cache: singletonObjects (level‑1), earlySingletonObjects (level‑2), and singletonFactories (level‑3).
When creating a Bean, Spring first registers a factory in the level‑3 cache. If a circular reference is detected, it obtains an early reference from the level‑3 cache, creates a partially initialized instance, stores it in level‑2, and later moves the fully initialized Bean to level‑1.
8. Explain the three‑level cache mechanism and its role in solving circular dependencies. Can only the second‑level cache solve the problem?
Key points :
Level‑1 cache (singletonObjects) : Stores fully initialized Bean instances. getBean first checks this cache.
Level‑2 cache (earlySingletonObjects) : Holds early references to Beans that are not yet fully initialized, allowing other Beans to depend on them during creation.
Level‑3 cache (singletonFactories) : Contains ObjectFactory objects capable of creating Bean instances on demand.
The resolution process:
When Bean A is being created, its factory is placed in level‑3.
If Bean A depends on Bean B, and Bean B depends back on A, Spring obtains A’s early reference from level‑3, creates a partially initialized A, and stores it in level‑2.
Bean B is then created (using the early reference of A if needed) and placed in the appropriate cache.
After B is fully created, Spring completes A’s initialization and moves it to level‑1.
The answer: No, the second‑level cache alone cannot solve circular dependencies because it lacks the factory needed to create the early reference; the third‑level cache is essential for pausing Bean creation and providing a factory‑based early reference.
9. How does Spring’s event mechanism work?
Key points :
Events enable decoupled communication between components.
Event classes extend ApplicationEvent. Publishing is done via ApplicationEventPublisher or directly through ApplicationContext.
When an event is published, Spring finds all Beans implementing ApplicationListener for that event type and invokes their onApplicationEvent method.
Events can propagate across parent‑child ApplicationContext hierarchies.
10. Explain the working principle of the @Transactional annotation and its transaction propagation behavior.
Key points : @Transactional enables declarative transaction management without explicit transaction code.
Spring creates a proxy for the annotated method; the proxy starts a transaction before method execution and commits or rolls back after execution.
Propagation options include REQUIRED (join existing or create new) and REQUIRES_NEW (always start a new transaction, suspending any existing one).
Implementation relies on AOP: Spring scans for @Transactional methods, creates proxies, and weaves transaction logic.
11. Explain the working principle of the @Async annotation and its asynchronous execution mechanism.
Key points : @Async marks a method for asynchronous execution.
Enabling async support (e.g., with @EnableAsync) registers a TaskExecutor that runs the method in a separate thread.
When the method is invoked, Spring submits the task to the configured TaskExecutor, which manages thread creation and execution.
12. How does the Spring MVC DispatcherServlet work?
Key points :
Request reception : Receives HTTP requests from clients.
Handler mapping : Uses HandlerMapping to locate the appropriate controller based on URL and parameters.
Handler execution : Invokes the selected controller (a POJO or more complex component).
View resolution : The controller returns a ModelAndView; ViewResolver resolves the view name to a concrete view technology (JSP, Thymeleaf, etc.).
View rendering : The resolved view renders the model data into HTML and sends the response back to the client.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer1970
Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
