Spring Core for Strong Senior Developers (Excluding Boot, Security, Data,
Cloud)
How does Spring's Dependency Injection (DI) work and what are the main
types?
Spring DI allows objects to be injected into other objects, promoting loose coupling.
Types of DI in Spring:
Constructor Injection — recommended for mandatory dependencies.
Setter Injection — useful for optional dependencies.
Field Injection — not recommended for testability and immutability reasons.
DI can be configured via XML, Java config (@Configuration + @Bean), or annotations
(@Component, @Autowired).
What is the difference between @Component, @Service, @Repository, and
@Controller in Spring?
All are specializations of @Component and used for auto-detection via component
scanning.
Differences lie in their semantic role and behaviors:
@Component — generic stereotype for any Spring-managed bean.
@Service — used for service layer beans; may be used by AOP for transactional
semantics.
@Repository — used for DAO layer; enables exception translation (via
PersistenceExceptionTranslationPostProcessor).
@Controller — used in web layer to mark controllers for Spring MVC.
How does Spring's ApplicationContext differ from BeanFactory?
Both are Spring containers for managing beans, but ApplicationContext extends
BeanFactory.
BeanFactory:
Basic container with lazy initialization.
Used in resource-constrained environments.
ApplicationContext:
Includes all features of BeanFactory.
Adds support for internationalization, event propagation, annotation scanning, and AOP.
Most applications use ApplicationContext (e.g., ClassPathXmlApplicationContext,
AnnotationConfigApplicationContext).
What is the role of @PostConstruct and @PreDestroy annotations in Spring
beans?
@PostConstruct:
Marks a method to be called after the bean has been constructed and dependencies
injected.
@PreDestroy:
Marks a method to be called before the bean is destroyed (during context shutdown).
Useful for initializing resources or cleaning up connections.
Alternative: implement InitializingBean and DisposableBean interfaces (not
recommended due to tight coupling with Spring APIs).
How does Spring handle circular dependencies and what are the limitations?
Spring can resolve circular dependencies for singleton beans using setter injection.
Mechanism:
Spring creates early references for beans during instantiation and wires them later.
Limitations:
Constructor-based injection with circular dependencies results in a
BeanCurrentlyInCreationException.
Prototype-scoped circular dependencies are not supported at all.
Best practices:
Refactor design to eliminate tight circular dependencies.
Use setter injection carefully if circular structure is unavoidable.