Spring Framework Spring Core & Dependency Injection 2 — Questions and Answers
Question 1: What annotation limits the @Autowired candidate beans to a specific name?
- @Primary
- @Qualifier (Correct answer)
- @Named
- @Specific
Correct answer: @Qualifier
@Qualifier is used alongside @Autowired to narrow down the injection candidate when multiple beans of the same type exist.
Question 2: Which interface must be implemented to create a custom BeanPostProcessor in Spring?
- BeanFactory
- ApplicationListener
- BeanPostProcessor (Correct answer)
- InitializingBean
Correct answer: BeanPostProcessor
Implementing the BeanPostProcessor interface allows custom logic to be applied before and after a bean's initialization callbacks.
Question 3: How do you specify the initialization method for a Spring bean in a @Bean definition?
- @Bean(init="methodName")
- @Bean(initMethod="methodName") (Correct answer)
- @Init("methodName")
- @PostConstruct only
Correct answer: @Bean(initMethod="methodName")
The initMethod attribute of @Bean specifies the name of the method to call after the bean is initialized by the container.
Question 4: What is the purpose of @Primary in Spring dependency injection?
- Marks a bean as the most important in the context
- Designates a bean as the default candidate when multiple beans of the same type exist (Correct answer)
- Gives a bean higher thread priority
- Ensures a bean is initialized first
Correct answer: Designates a bean as the default candidate when multiple beans of the same type exist
@Primary designates a bean as the preferred candidate for auto-wiring when multiple beans of the same type are present in the container.
Question 5: What is a Spring bean's lifecycle callback that executes before the bean is destroyed?
- @PreRemove
- @Finalize
- @PreDestroy (Correct answer)
- @BeforeDestroy
Correct answer: @PreDestroy
@PreDestroy marks a method to be called just before the bean is removed from the container, allowing cleanup of resources.
Question 6: In Spring, what is meant by 'circular dependency'?
- A bean that references itself
- Two or more beans that depend on each other either directly or indirectly (Correct answer)
- A bean scope that repeats initialization
- A proxy bean wrapping another proxy
Correct answer: Two or more beans that depend on each other either directly or indirectly
A circular dependency occurs when Bean A depends on Bean B and Bean B depends on Bean A, which can cause Spring to throw a BeanCurrentlyInCreationException with constructor injection.
What annotation limits the @Autowired candidate beans to a specific name?