In a multi-threaded Spring application with singleton beans, what thread-safety consideration must be kept in mind?
ASingleton beans are automatically thread-safe by Spring
BDevelopers must ensure singleton bean implementations are thread-safe
CUse synchronized keyword on all methods in singleton beans
DConvert singleton beans to prototype scope for thread safety
Correct Answer:
B. Developers must ensure singleton bean implementations are thread-safe
EXPLANATION
Spring doesn't enforce thread-safety for singleton beans. Developers must implement thread-safe code, use immutable objects, or utilize synchronization where necessary.
Consider a Spring application where you need different bean implementations based on the deployment environment. Which approach is most suitable?
AUse @Profile annotation on bean definitions
BUse @Conditional annotation with custom conditions
CUse @ConditionalOnProperty for property-based selection
DAll of the above are valid approaches
Correct Answer:
D. All of the above are valid approaches
EXPLANATION
@Profile is for environment-based activation, @Conditional for custom logic, and @ConditionalOnProperty for property-driven bean registration. Choice depends on specific requirements.
In a complex Spring application, when would you prefer to use ObjectFactory over direct bean injection?
ATo get a new instance of the bean each time it's accessed
BTo defer bean creation until it's actually needed
CTo break circular dependencies between beans
DAll of the above scenarios
Correct Answer:
D. All of the above scenarios
EXPLANATION
ObjectFactory enables lazy initialization, provides new instances for prototype beans, and can help resolve circular dependencies through deferred access.
A microservices architecture uses Spring with circular dependency between ServiceA and ServiceB. What is the best solution?
AIncrease heap memory to handle circular references
BRefactor to introduce a third service or use setter injection with @Lazy
CUse @Autowired on both constructor and setter
DSwitch to manual bean management
Correct Answer:
B. Refactor to introduce a third service or use setter injection with @Lazy
EXPLANATION
Circular dependencies indicate design issues. Best solutions: refactor code, use setter injection (instead of constructor) combined with @Lazy, or introduce an intermediary service to break the cycle.
In Spring Framework 2024-25, which feature allows lazy initialization of beans?
A@Lazy annotation on @Bean or @Component
B@DeferredInit annotation
CSetting lazy-init='true' only in XML
DSpring automatically detects and lazily initializes all beans
Correct Answer:
A. @Lazy annotation on @Bean or @Component
EXPLANATION
@Lazy annotation (available in modern Spring versions) marks beans for lazy initialization. It can be used on class level or with @Bean methods. XML also supports lazy-init attribute.