Spring Framework Spring Core & Dependency Injection 1 — Questions and Answers
Question 1: Which Spring annotation is used to mark a class as a Spring-managed component?
- @Component (Correct answer)
- @Bean
- @Autowired
- @Service
Correct answer: @Component
@Component is the generic stereotype annotation that marks a class as a Spring-managed bean eligible for component scanning.
Question 2: What is the default bean scope in Spring Framework?
- prototype
- singleton (Correct answer)
- request
- session
Correct answer: singleton
By default, Spring beans are singletons, meaning the IoC container creates exactly one instance of the bean per Spring container.
Question 3: Which annotation is used to inject dependencies in Spring?
- @Resource
- @Inject
- @Autowired (Correct answer)
- @Value
Correct answer: @Autowired
@Autowired is Spring's annotation for automatic dependency injection by type into fields, constructors, or setter methods.
Question 4: What does the @Configuration annotation indicate in Spring?
- The class contains request mappings
- The class is a source of bean definitions (Correct answer)
- The class should be proxied
- The class handles exceptions
Correct answer: The class is a source of bean definitions
@Configuration marks a class as a source of bean definitions, allowing @Bean methods to be declared inside it for the Spring IoC container.
Question 5: In Spring, what is the difference between constructor injection and setter injection?
- Constructor injection supports optional dependencies; setter injection does not
- Setter injection creates immutable objects; constructor injection does not
- Constructor injection enforces mandatory dependencies at creation time; setter injection allows optional wiring (Correct answer)
- There is no functional difference between the two
Correct answer: Constructor injection enforces mandatory dependencies at creation time; setter injection allows optional wiring
Constructor injection makes dependencies mandatory and supports immutability, while setter injection is used for optional dependencies that can be changed after object creation.
Question 6: What is the ApplicationContext in Spring Framework?
- A database connection pool
- An advanced IoC container that adds enterprise features on top of BeanFactory (Correct answer)
- A web request handler
- A configuration file parser
Correct answer: An advanced IoC container that adds enterprise features on top of BeanFactory
ApplicationContext is Spring's advanced IoC container that extends BeanFactory with features like event publishing, i18n, and AOP integration.
Which Spring annotation is used to mark a class as a Spring-managed component?