Spring Framework Core Interview Questions and Answers

In this post, we will discuss important Spring core interview questions with answers. In this article, I will cover interview questions and answers for Spring core concepts such as Dependency Injection, Spring IOC container, and Aspect-Oriented Programming (AOP).

These interview questions had asked many times in interviews so I hope you guys find them useful.

1. What is the Spring Framework?

In short, Spring is an Integration Framework for developing Enterprise Applications easily.
Spring framework simplifies the complexity of enterprise applications because it uses Java beans to implement enterprise applications that were previously possible only with enterprise beans.
Spring is an Open Source framework, developed by Rod Johnson.

2. What are the benefits of using Spring?

Spring targets to make Java EE development easier. Here are the advantages of using it:
  • Lightweight: Lightweight development with Java POJOs.
  • Inversion of Control (IoC): Spring container takes care of wiring dependencies of various objects, instead of creating or looking for dependent objects
  • Aspect-Oriented Programming (AOP): Spring supports AOP to separate business logic from system services
  • IOC container: It is responsible for instantiating, configuring, and assembling the Spring beans by reading configuration metadata
  • MVC framework: that is used to create web applications or RESTful web services, capable of returning XML/JSON responses
  • Transaction management: reduces the amount of boiler-plate code in JDBC operations, file uploading, etc., either by using Java annotations or by Spring Bean XML configuration file
  • Exception Handling: Spring provides a convenient API for translating technology-specific exceptions into unchecked exceptions

3. What is Dependency Injection?

In simple terms, Dependency Injection an aspect of Inversion of Control (IoC), is a general concept stating that you do not create your objects manually but instead describe how they should be created. An IoC container will instantiate required classes if needed.
From Spring documentation - Dependency injection (DI) is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. 
This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies on its own by using direct construction of classes, or the Service Locator pattern.

4. How do we implement DI in Spring Framework?

There are three ways we can do a spring configuration:
  • XML-based configuration
  • Annotation-based configuration
  • Java-based configuration
We can use the above configurations to implement DI in spring applications. For a better understanding, please read the https://www.javaguides.net/2018/06/guide-to-dependency-injection-in-spring.html article.

5. How can we inject beans in Spring?

Spring provides different options to inject beans:
  1. Setter-based Injection
  2. Constructor-based Injection
  3. Field-based Injection
The spring configuration can be done using XML files or annotations or Java configuration. 

Read more about setter-based injection at Spring Dependency Injection via Setter Example

Read more about constructor-based injection at Spring Dependency Injection via Constructor Example.

6. What is the Spring IOC container?

The Spring IOC container is responsible for instantiating, configuring, and assembling the Spring beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. 
The configuration metadata is represented in XML, Java annotations, or Java code. It lets you express the objects that compose your application and the rich interdependencies between those objects.
Read more about Spring IOC container at Spring IOC Container Overview.

7. What are the responsibilities of the Spring IOC Container?

The responsibilities of the IOC container are:
  • Instantiating the bean
  • Wiring the beans together
  • Configuring the beans
  • Managing the bean’s entire life-cycle
Read more about Spring IOC container at Spring IOC Container Overview.

8. What are the Advantages of Dependency Injection?

  • Decoupling: Code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies.
  • Easier to test: As such, your classes become easier to test, in particular when the dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations to be used in unit tests.

9. How to Create a Spring Container?

Spring provides many ApplicationContext interface implementations that we use are;
  1. AnnotationConfigApplicationContext: If we are using Spring in standalone Java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
  2. ClassPathXmlApplicationContext: If we have a spring bean configuration XML file in a standalone application, then we can use this class to load the file and get the container object.
  3. FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the XML configuration file can be loaded from anywhere in the file system.
AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
Let's write a code to create a Spring container:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Note that we are supplying configuration metadata via the applicationContext.xml file(XML-based configuration).
AnnotationConfigApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
Note that we are supplying configuration metadata via AppConfig.class file.
The most used API that implements the BeanFactory is the XmlBeanFactory.
 XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("applicationContext.xml"));

10. How to Retrieve Bean from Spring Container?

Both BeanFactory and ApplicationContext interface provides a getBean() method to retrieve bean from the spring container.
ApplicationContext getBean() Example:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
BeanFactory getBean() Example:
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("beans.xml")); 
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld"); 

11. What are the different types of dependency injections in spring?

1. Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.
In the below diagram, the highlighted code shows a Constructor-based dependency injection example.
2. Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
In the below diagram, the highlighted part shows the setter-based dependency injection.
Read more about setter-based injection at Spring Dependency Injection via Setter Example

Read more about constructor-based injection at Spring Dependency Injection via Constructor Example.

12. When to Use Constructor-based and Setter-based DI in Spring?

From spring Framework documentation, since we can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the @Required annotation on a setter method can be used to make the property a required dependency.
Which of these DI methods is better purely depends on your scenario and some requirements. The following best practices may provide a guideline:
  1. Use constructor-based DI for mandatory dependencies so that your bean is ready to use when it is first called. 
  2. When your constructor gets stuffed with a large number of arguments, it's the figurative bad code smell. It's time to break your bean into smaller units for maintainability. 
  3. Use setter-based DI only for optional dependencies or if you need to reinject dependencies later, perhaps using JMX. 
  4. Avoid circular dependencies that occur when a dependency (say, bean B) of your bean (bean A) directly or indirectly depends on the same bean again (bean A), and all beans involved use constructor-based DI. You may use setter-based DI here. 
  5. You can mix constructor-based and setter-based DI for the same bean, considering mandatory, optional, and circular dependencies. 
In a typical Spring application, you can see dependencies injected using both approaches, but this depends on the scenario, considering the preceding guidelines.

13. What is the difference between BeanFactory and ApplicationContext in the Spring framework?

  • One main between BeanFactory and ApplicationContext is that BeanFactory only instantiates bean when we call getBean() method while ApplicationContext instantiates singleton bean when the container is started, It doesn't wait for getBean() method to be called.
  • BeanFactory uses a lazy initialization approach whereas ApplicationContext uses an eager initialization approach.
  • The below diagram summarize the features provided by BeanFactory and ApplicationContext interfaces and implementations:

Read more at BeanFactory vs ApplicationContext in Spring.

14. What is a Spring Bean?

The Spring Beans are Java Objects that are initialized by the Spring IoC container.

15. What is the default bean scope in the Spring framework?

By default, a Spring Bean is initialized as a singleton.

16. What are the types of Spring IOC containers?

Spring provides the following two distinct types of containers.
  • BeanFactory container
  • ApplicationContext container
Read more about the BeanFactory interface at Spring BeanFactory Interface Example.
Read more about ApplicationContext at BeanFactory vs ApplicationContext in Spring.

17. Are singleton beans thread-safe?

No, singleton beans are not thread-safe, as thread safety is about execution, whereas singleton is a design pattern focusing on creation. Thread safety depends only on the bean implementation itself.

18. What are the different scopes of Spring Beans?

Spring Framework supports the following bean scopes :
  • singleton: (Default) Scopes a single bean definition to a single object instance per Spring IoC container
  • prototype: Scopes a single bean definition to any number of object instances
  • request: Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext
  • session: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext
  • application: Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext
  • WebSocket: Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.


19. What Is Aspect-Oriented Programming (AOP)?

Aspect-oriented programming is a programming paradigm that tries to solve problems with cross-cutting concerns. Aspect-oriented programming (AOP) complements object-oriented programming (OOP) by providing a different way to think about program structure.

Basically, enterprise applications have some common cross-cutting concerns that are applicable to different types of Objects and application modules, such as logging, transaction management, data validation, authentication, etc. In Object-Oriented Programming, the modularity of the application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different class methods.

20. What is a cross-cutting concern?

A cross-cutting concern is a functionality that is tangled with business code, which usually cannot be separated from the business logic. Auditingsecurity, and transaction management are good examples of cross-cutting concerns. They are mingled with the business code, heavily coupled with the functionality that might be affected if they fail. These are good candidates for separation using aspects because there is no design pattern that would allow writing the code in such a way that they would be separated from the business logic.
Examples of cross-cutting concerns:
  • Logging
  • Security
  • Transaction management
  • Auditing,
  • Caching
  • Internationalization
  • Error detection and correction
  • Memory management
  • Performance monitoring
  • Synchronization

21. What are Aspect, Advice, Pointcut, JointPoint, and Advice Arguments in AOP?

Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in the Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.

Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that get executed when a specific join point with a matching pointcut is reached in the application. You can think of Advice as Spring interceptors or Servlet Filters.

Pointcut: Pointcut is regular expression that are matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.

JoinPoint: A join point is a specific point in the application such as method execution, exception handling, changing object variable values, etc. In Spring AOP a join point is always the execution of a method.

Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where the argument type is determined.

In order to understand the above AOP terminologies with an example, check my separate article at Understanding Spring AOP Concepts and Terminology with Example.

Comments