Spring Boot Core Container and Beans 2 — Questions and Answers
Question 1: Which annotation marks a method as a bean producer inside a @Configuration class?
- @Bean (Correct answer)
- @Component
- @Service
- @Produces
Correct answer: @Bean
@Bean annotates methods in @Configuration classes so Spring registers the return value as a managed bean.
Question 2: What is the default bean scope in a Spring ApplicationContext?
- prototype
- singleton (Correct answer)
- request
- session
Correct answer: singleton
Spring beans default to singleton scope, meaning one shared instance per ApplicationContext.
Question 3: Which interface can a bean implement to run code immediately after the ApplicationContext is fully started?
- InitializingBean
- ApplicationRunner (Correct answer)
- BeanPostProcessor
- SmartLifecycle
Correct answer: ApplicationRunner
ApplicationRunner's run() method is called after the context is refreshed and the application is ready.
Question 4: What happens when two beans of the same type exist and an @Autowired field has no @Qualifier?
- Spring picks the first one alphabetically
- Spring throws NoUniqueBeanDefinitionException (Correct answer)
- Spring injects null
- Spring creates a new bean on the fly
Correct answer: Spring throws NoUniqueBeanDefinitionException
Without a qualifier Spring cannot choose between two matching beans and throws NoUniqueBeanDefinitionException.
Question 5: Which annotation would you add to a bean so Spring always creates a fresh instance for every injection point?
- @Singleton
- @Prototype
- @Scope("prototype") (Correct answer)
- @Transient
Correct answer: @Scope("prototype")
@Scope("prototype") tells Spring to create a new bean instance each time it is requested.
Question 6: What does the @Lazy annotation do when placed on a @Bean method?
- Creates the bean asynchronously
- Defers bean initialization until first use (Correct answer)
- Marks the bean as optional
- Reduces bean memory footprint
Correct answer: Defers bean initialization until first use
@Lazy delays instantiation of the bean until it is first requested from the context.
Question 7: Which Spring annotation is a specialization of @Component intended for data-access classes?
- @Service
- @Controller
- @Repository (Correct answer)
- @Mapper
Correct answer: @Repository
@Repository marks DAO classes and additionally enables Spring's persistence exception translation.
Which annotation marks a method as a bean producer inside a @Configuration class?