avatarGerald Nguyen

Summary

The provided web content presents a concise guide on essential Spring IoC interview questions, aimed at evaluating practical skills expected in a Spring-based work environment.

Abstract

The article outlines five critical Spring Inversion of Control (IoC) interview questions, focusing on dependency injection, bean lifecycle, and resolution of common configuration errors. It emphasizes the importance of understanding Spring's DI mechanism, proper injection of Prototype beans into Singletons, strategies to resolve bean duplication conflicts, bean lifecycle management within the Spring IoC container, and Spring's methods for detecting beans in an application. The guide is part of a larger series intended to prepare both interviewers and interviewees by covering real-world scenarios and best practices in Spring IoC.

Opinions

  • The author suggests that a solid grasp of Dependency Injection is a minimum requirement for candidates, with experienced individuals expected to understand its benefits and optimal usage for maintainable and testable code.
  • On the topic of injecting Prototype beans into Singletons, the author conveys that inexperienced candidates might not be aware of the intricacies involved and may require a deeper understanding to avoid common pitfalls.
  • The article implies that experienced Spring developers should be familiar with the "expected single matching bean but found 2" error and knowledgeable about various solutions to resolve it.
  • It is the author's view that understanding the Spring bean lifecycle, including its initialization and destruction phases, is crucial for a candidate's familiarity with Spring IoC container.
  • The author opines that knowledge of component scanning and annotations like @Component, @Service, @Repository, @Controller, and @Configuration is essential for identifying and configuring Spring beans.
  • The guide advocates for the use of specific annotations and methods for customizing bean lifecycle, suggesting that these are best practices in Spring development.
  • The author's inclusion of a link to a more detailed article on resolving Spring dependency errors indicates a belief that further reading on the subject will be beneficial to the reader.
  • Lastly, the author encourages readers to subscribe and follow for more content, indicating a commitment to providing ongoing value and resources for interview preparation.

Five Minimum Viable Spring IoC Interview Questions

Interviewer: ask them if your interview is running out of time. Interviewee: practice them if your preparation is running out of time.

Photo by Maranda Vandergriff on Unsplash

This is part of my Five Minimum Viable Interview Questions series where I research and compile Five essential interview questions on each interview topic. All of these questions aim to assess real and practical skills expected at work

#1 — What is Dependency Injection?

Dependency Injection (DI) is a fundamental concept in Spring and thus is a minimum “know” that a candidate must possess. Good candidates, in addition, should be able to elaborate on how Spring implements DI and manage objects. Experienced candidate should be able to elaborate its benefits and its proper usage to maximize the benefits

DI is a design pattern and a software engineering technique for achieving Inversion of Control (IoC) in the Spring framework. The main purpose of dependency injection is to decouple objects from each other and make the code more flexible, maintainable, and testable.

Instead of an object creating or controlling its dependencies, the framework manages the object's dependencies and injects them into the object via the object’s constructors, setters, or internal fields. This is known as constructor injection, setter injection, and field injection respectively. Spring originally uses XML-based configuration files to declaratively manage object dependencies. In later versions, Spring supported annotation, Java-based configuration, auto-wiring, and auto-scanning to reduce the number of explicit configurations.

In most cases, Spring is even responsible for creating the object and its dependencies and managing their lifecycles. Generally, each bean in Spring IoC has either Singleton or Prototype scope. Web applications utilizing the Spring framework may have extra scopes such as Request, Session, and Application scope.

Dependency injection has many benefits, including:

  • Improving testability by making it easier to substitute fake objects for real ones.
  • Making it easier to change implementations of a particular dependency without affecting the rest of the code.
  • Promoting code reuse by making it possible to use the same implementation in multiple places.

#2 — How do you declare or inject a Prototype bean into a Singleton?

This question tests candidate’s understanding of Singleton and Prototype scopes, how Spring creates and manage their instances, and how Spring resolves dependencies. Inexperienced candidates may not know that the default injection is insufficient.

A Singleton bean has exactly 1 instance per Spring IoC container. For a typical Spring application, only 1 instance of that bean is ever created. On the contrary, an instance of a Prototype bean is created every time a dependency for that bean is injected. Singleton bean is usually used for stateless operations while Prototype bean is for stateful operations.

If we use the default injection mechanism to inject a Prototype bean into a Singleton, we can end up in a situation where a single instance of the Prototype bean is associated with the Singleton bean throughout the Singleton life. This is probably incorrect and may result in concurrency bugs.

There are 2 common ways to correctly obtain a new instance of Prototype bean in a Singleton bean:

  • Declare a dependency to ApplicationContext in the Singleton and use this ApplicationContext.getBean(...) method to obtain the fresh Prototype bean instance.
  • Declare a Lookup method with the @Lookup(...) annotation. Spring automatically overrides the method using CGLIB bytecode generation to provide the necessary bean lookup at runtime.

#3 — How do you resolve “expected single matching bean but found 2” error?

This question assesses how extensive a candidate has use Spring IoC container. Experienced candidate must have encountered this error and know how to fix it. Good candidates should be able to list out a few different solutions.

This error happens when Spring found multiple beans matching the dependency declaration. If both InMemoryStore and DatabaseStore implements the same UserRepository interface, attempting to resolve an UserRepository dependency in AuthenticationManager will fail with this error because Spring found 2 beans matching the expected dependency.

A simple way to fix this error is to designate a primary bean by applying the @Primary annotation on the chosen one. Spring IoC will pick the primary bean if it found multiple beans matching the same dependency declaration.

Another popular fix is to tell Spring the exact name of the dependency bean to inject. By applying the @Qualifier(<bean name>) annotation on the constructor or setter’s dependency parameter or the field, we ensure that Spring IoC will resolve to only one bean thus avoiding the error.

Other solutions include:

  • Accepting multiple beans
  • Explicit Bean configuration
  • (Advanced) Feature Switching

If you are curious, I recommend a visit to the below article for more solutions and code samples

#4 — Please describe a bean lifecycle within a Spring IoC

This question assesses a candidate’s familiarity with bean lifecycle and the various ways it can be customized through callback methods

The lifecycle of a bean within the Spring IoC container is a sequence of events that starts with the creation of a bean and ends with the destruction of the bean. The lifecycle of a bean can be customized through various callbacks, such as init and destroy methods.

The bean lifecycle within the Spring IoC container contains 4 main phases:

  • Bean instantiation: creating a new instance of the bean. This includes resolving and injecting its dependencies.
  • Bean initialization: If specified, the IoC container can invoke the initialization callback method on the created instance. The bean class can implement the afterPropertiesSet() method of InitializingBean interface, or applying a @PostConstruct() annotation on a method, or name that method in the initMethod attribute of the @Bean() annotation (or its init-method XML configuration counterpart)
  • Bean in use: by other objects in the application
  • Bean destruction: If specified, the IoC container can invoke the destruction cal back method on the bean instance prior to removing it from the container. The bean class can implement the destroy() method of DisposableBean interface, or applying a @PreDestroy() annotation on a method, or name that method in the destroyMethod attribute of the @Bean() annotation (or its destroy-method XML configuration counterpart).

#5 — How does Spring detect a bean in an application?

Spring offers various ways to mark a plain Java object as a Spring bean. This question tests the candidate’s knowledge in this regard. More experienced candidates should be able to offer a more extensive answer and elaborate on their appropriate uses.

Spring detects beans in an application through component scanning. Component scanning is the process by which the Spring IoC container searches for and identifies classes that are annotated with specific annotations, such as@Component, @Service, @Repository, @Controller, @Configurationetc.

These annotations are all meta-annotations of the @Component annotation and provide additional meaning and context for the classes that are annotated with them.

  • @Component: is a general-purpose annotation that is used to indicate that a class is a candidate for component scanning.
  • @Service: indicate that a class is a service class. A service class is a class that provides a service to other components in the application. Service classes are typically business-oriented and perform a specific task.
  • @Repository: indicate that a class is a data repository class. A repository class is a class that provides access to data stored in a database or other persistence mechanism.
  • @Controller: indicate that a class is a controller class. A controller class is a class that handles incoming requests from clients and returns a response. Controllers are typically used in web applications to handle user requests and return views or data.
  • @Configuration: indicate that a class is a configuration class. A configuration class is a class that contains configuration information for the application. Configuration classes can be used to configure beans and other aspects of the application.

To enable component scanning in a Spring application, we can either apply the <context:component-scan base-package="<package-to-scan>"> element in the XML configuration file. Or in the case of Java and annotation-based configuration, applying the @ComponentScan(<base-package>) on a @Configuration class. If we specify com.example as the base package, Spring IoC will search for classes annotated with @Component, @Service, @Repository, @Controller, @Configurationetc in the com.example package and its sub-packages.

Within a @Configuration class, we can create additional bean definitions by applying the @Bean() annotation to its instance method. These bean definitions are automatically incorporated into the active IoC container.

Visit my Five Minimum Viable Interview Questions series for more interview topics.

Subscribe now to get my latest article delivered to your mailbox

Follow 50LD for more quality articles and interview preparation tips

Join Medium to enjoy limitless reading of quality articles

Thank you.

Interview
Spring
Ioc
Questions
Java
Recommended from ReadMedium