Top Java Spring Framework Interview Questions and Answers (Updated 2021)

Are you curious to learn about the Java Spring framework? Or are you looking for Java Spring interview questions for your next job change? Do you need to brush up your Spring concepts for the next team meeting? Then this blog answers most of your Java Spring queries. Well, not all, because this isn’t a Java Spring tutorial! 

However, we will be covering Java Spring Interview questions commonly asked during interviews. If you aim to look at a particular topic in the Spring framework, we have divided the contents under different sections: 

  • General Java Spring Interview Questions 
  • Dependency Injection (DI) or Inversion of Control Interview Questions 
  • Java Spring Beans Interview Questions 
  • Java Spring Annotations Interview Questions 
  • Java Spring Data Access Interview Questions
  • Java Spring Aspect-Oriented Programming (AOP) Interview Questions 
  • Java Spring Model View Controller Interview Questions

General Java Spring Interview Questions

What is the Spring Framework? 
Spring is an open-source and lightweight framework for application development in Java enterprise edition. Spring develops high-quality, reliable, and reusable applications. Spring Framework contains a lot of pre-written generic code. This makes it popular among programmers for faster and efficient application development. It is rightly called the framework of frameworks as it provides support to other Java frameworks like Hibernate, Struts, EJB, JSF, etc. 


What are the 
several features and advantages of the Java Spring Framework? 
Spring Framework features: 

  • Inversion of Control (IoC): IoC means that the object within your code does not depend on the objects of other classes; however, it may know the abstract implementation i.e. interface for these objects for future purposes. 
  • Aspect-Oriented Programming (AOP): It is a software paradigm that separates business logic from the various functions in an application.  
  • Container: Container is at the core of the Spring Framework. It creates application objects and configures them. The container manages the application lifecycle from creation till destruction.  
  • Data Access Framework:  Developers have the provision to use Persistence API, like JDBC, Hibernate, etc in Spring Framework.  It takes care of several database related things like enabling interaction with the DB connection, making sure of a closed connection, and dealing with exceptions. 
  • Transaction Management: The framework provides an abstraction layer for transaction management. Both, container as well as containerless environments can gain from this layer. 
  • JDBC Exception Handling: It eases the error handling mechanism by offering an exception hierarchy through the JDBC abstraction layer. 
  • Model-View-Controller (MVC) Framework: Java Spring Model View Controller is a software design pattern that is extremely configurable. Due to this feature, it can easily integrate with other frameworks and benefit the most through reusability.  

 
Due to the features that Java Spring Framework offers, there are several advantages of using Java Spring as listed below.  

  • Ease of code and faster application development. 
  • Reusable applications. 
  • Loose coupling between applications due to Dependency Injection. 
  • Applications developed through Spring are easy to test. 
  • It is a lightweight framework as it provides the Plain Old Java Object (POJO) implementation for continuous integration. 
  • Powerful abstraction for Java Enterprise Edition specification likes JDBC, JM, JPA, etc. 
  • An open-source framework resulting in flexibility and agility. 


What are the various Spring modules in Java
? 
Spring framework offers many features and organizes them into 20 Spring Modules in Java.The below diagram depicts the classification of Java Spring Framework modules.  

Java Spring Framework Overview
Image from https://docs.spring.io/

 

Spring Modules in Java Overview: 

  • Core Container: The Core Container is at the heart of the Spring modules in Java and consists of Spring Core, Spring Beans, Context, and Spring Expression Language(SpEL) modules. 
  • Spring Core and Spring Beans– Responsible for the fundamental features of Spring i.e., Inversion of Control and Dependency Injection.  
  • Context- Inherits its features from Java Beans and aids in accessing objects within the framework.  
  • SpEL-  Queries and updates an object graph during execution.   
  • Data Access/Integration 
  • JDBC– With its abstraction layer reduces the effort of coding JDBC related operations.  
  • ORM provides several APIs for object-relational mapping. 
  • OXM– Abstraction layer provides support to XML or Object mapping. 
  • Java Messaging Service(JMS)– Creates and consumes messages. 
  • Transaction– Manages various transactions within the classes. 
  • Web 

 

The Web layer extends the functionality to create web-applications through the Web, Web-Servlet, Web-Socket, and Web-Portlet modules. 

  • AOP and Instrumentation 
  • Spring AOP– Provides you the ability to write loosely coupled code through method-interceptor, Advice, Pointcut, etc.  
  • Instrumentation– Offers support and implementation for class instrumentation and classloader. 
  • Test 

This module enables and enhances the testing capabilities of Spring components with JUnit or TestNG.  

What components does a Spring application have?
A Spring application consists of the following components: 

  • The framework interface that defines all the functions. 
  • The Java Bean class that consists of getter() and setter() methods. 
  • Spring AOP Framework. 
  • The Bean Configuration File that maintains the information of classes and the means to configure them. 
  • User programs that consume various functions. 

 

What is a Spring Configuration file? 
The configuration file is an XML file that the Spring Container uses for managing the lifecycle of the Java Bean. It helps in attaining dependency injection as well. It contains information related to classes, interfaces, and their dependencies.  

The Beans.xml file assigns a unique ID to each Java Bean and controls creation of various instances of objects. Let us see how a configuration file looks like:

<?xml version = "1.0" encoding = "UTF-8"?> 

 <beans xmlns = "http://www.springframework.org/schema/beans" 

   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 

   xsi:schemaLocation = "http://www.springframework.org/schema/beans 

   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 

   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"> 

      <property name = "message" value = "Hello World!"/> 

   </bean> 

 </beans> 

Using the above configuration file, you can print different values for the “message” variable without impacting the Spring source files.

 

Java Spring interview questions: Dependency Injection (DI) or Inversion of Control

What is a Java Spring IoC Container? 
The Java Spring Inversion of Control container lies at the heart of the Java Spring Framework. The interface org.springframework.context. ApplicationContext represents the Spring IoC container. It instantiates classes, configures and wires the objects of those classes, and manages their life cycle from inception, execution, until destruction. The IoC container manages the various components and modules of an application through Java Beans. 

The Java Spring Inversion of Control container knows which object it needs to instantiate, configure, and assemble by reading the configuration metadata provided in the form of XML, annotations, or code. Below is a diagrammatic representation of how Spring works. 

Java Spring Framework IOC Container

 

What are the types of Spring IoC containers? 
The two types of containers that the Java Spring Framework provides are: 

  • Spring BeanFactory Containerr: The interface org.springframework.beans.factory. BeanFactory defines the BeanFactory Container. It is the simplest container that provides the elementary support for Dependency Injection. This container is a collection of Beans in the form of interfaces like BeanFactoryAware, InitializingBean, DisposableBean, etc. 
  • Spring ApplicationContext Container: This container builds on the top of the BeanFactory container. It offers additional enterprise-specific functionality to interested event listeners. The interface org.springframework.context. ApplicationContext defines this container. 

 

What is Dependency Injection(DI) and what are the ways to achieve it? 
We often use the terms IoC and Dependency Injection in Java interchangeably. However, Dependency Injection in Java is a form of Inversion of Control, where you pass the implementations to an object via constructors, setters or, service lookups without actually creating the object. You don’t connect the components and services of an application programmatically, instead, you define in the configuration file which components require which service. The IoC container plays its part by wiring the components and services together. There are two types of Dependency Injection in Java Spring: 

  • Constructor Injection: The container invokes an argument constructor that represents a dependency that you want to set. 
  • Setter Injection: The container instantiates the Bean by invoking a no-argument constructor or a non-argument static factory method and then calling the setter() methods of a class. 

There is a third DI called Interface Injection, but it is not available in Java Spring. 

What are the advantages of using IoC? 
Few advantages of IoC are: 

  • IoC minimizes the lines of code in your application. 
  • The application becomes easily testable as IoC does not require singletons or JNDI lookup mechanisms in the unit test cases. 
  • It enables loose coupling with the slightest effort and less intrusive mechanism. 
  • It supports the eager instantiation and lazy loading of the services. 

Java Spring Beans Interview Questions

What are the differences between BeanFactory and ApplicationContext

In Spring, beans are objects that are at the heart of your application. The IoC container instantiates, assembles, and manages the bean object.  When the container creates the bean, the information related to them and their dependencies are also reflected in the configuration metadata. The configuration metadata is then provided to the IoC container for further reference. 

 The definition of the Bean contains the configuration metadata, which informs the container about the following things: 

  • How to create a bean 
  • Bean’s life cycle details 
  • Bean’s dependencies. 

 

 

 

 

What is the Bean life cycle in a Spring Bean Factory Container? 

 

Java-Spring-Framework-Bean-lifecycle
Image from Oreilly

Spring BeanFactory controls the creation and destruction of beans. It manages the life cycle of beans through the Spring container:  

  • Instantiate: As soon as a container starts, it instantiates a Spring bean, based on Java or XML definitions. 
  • Populate Properties: The dependency injection populates the requisite properties specified in the bean definition.  
  • BeanNameAware: The bean factory calls the method setBeanName() by passing the bean’s ID if the bean implements the BeanNameAware interface. 
  • BeanFactoryAware: This step depends on whether the bean implements the BeanFactoryAware interface or not. If yes, then the factory invokes the method setBeanFactory() by passing its instance. 
  • ApplicationContextAware: This interface allows beans to access the ApplicationContext container. 
  • Initialization BeanPostProcessors: The container checks whether the implementation of BeanPostProcessors defines the bean or not. If yes, then it invokes the preProcessBeforeInitialization() method. 
  • Call custom init-method: The container calls the customized init-method if the bean defines one such method. 
  • Post-Initialization BeanPostProcessors: Finally,  if Bean associates with BeanPostProcessors,then the container calls the postProcessBeforeInitialization().  
  • destroy() method of DisposableBean Interface: This method destructs all the associated resources after the execution of the bean. 
  • Call custom destroy() method: This is an alternative to the default destroy() method of DisposableBean interface to destruct all resources. 

 

Differentiate between singleton and prototype bean scope?
Singleton: Spring creates a single instance for a bean definition per Spring IoC container. The same object instance will be shared for every bean request. This is the default scope for Spring beans. 

Prototype: In the case of prototype scope, Spring creates a new object instance each time the application requests the bean. Thus a single bean definition can have several object instances associated with it. 

 

Java Spring Interview Questions: Annotations

What is Annotation-based container configuration?
You can use Spring annotations in Java for relevant class, method, or variable and bring the bean configuration into the component class.  

The container performs annotation injection before XML injection. Thus, the annotation configuration will override the properties set through XML configuration. 

 Annotation wiring is not the default setting in Spring. So, before being able to use it,  you need to enable it in the Spring configuration file.  

 A configuration file for Spring annotations in Java will look like this: 

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans" 

   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 

   xmlns:context = "http://www.springframework.org/schema/context" 

   xsi:schemaLocation = "http://www.springframework.org/schema/beans 

   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 

   http://www.springframework.org/schema/context 

   http://www.springframework.org/schema/context/
spring-context-3.0.xsd"> 

   <context:annotation-config/> 

   <!-- bean definitions go here --> 

</beans> 

 

What are the various Spring Annotations in Java? 
There are several DI based and context-configuration based Spring annotations in Java

 DI based annotations 

  • @Autowired: This annotation marks a dependency which Spring has to resolve and inject. You can use it with a constructor, setter, or field injection. 
  • @Bean: This annotation marks the factory method that instantiates a bean. 
  • @Qualifier: The @Autowired uses the @Qualifier to resolve ambiguous situations by providing the bean id or bean name. 
  • @Required: All setter methods require this annotation otherwise to mark dependencies that we aim to populate through XML. 
  • @Value: This annotation property values into beans. You can use it with a constructor, setter, or field injection. 
  • @DependsOn: If Spring initializes another bean before the annotated one, then it uses this annotation. 
  • @Lazy: You use this annotation when you want to initialize the bean lazily. It means that you don’t want the application to create the bean at startup. Instead, you want that the application should create a bean on user request. By default, Spring beans initialize on startup. Thus, to instruct Spring otherwise, we use @lazy. 
  • @Lookup: A method that uses @Lookup instructs Spring bean to return an instance of the method’s return type on invocation. 
  • @Primary: The @Primary marks the most frequently used bean so that the system will know which bean it has to use in case of multiple beans of the same type. 
  • @Scope:  As the name suggests, it defines the scope of a component class or a Bean definition. The scope can be a singleton, prototype, request, session, global session, or can be some custom scope. 

Context-configuration based annotations 

  • @Configuration: Indicates that a class defines one or more @Bean methods that the container can execute.  
  • @Profile: By using this annotation, a component becomes eligible for bean registration when one or more specified profiles are active. Profile here refers to a logical group of beans. 
  • @Import: Enables one or more components to import configuration classes. You can also import a class containing at least one bean method definition. 
  • @ImportResource: Use this annotation to import resources containing bean definitions. 

 

Java Spring Interview Questions: Data Access

Explain Java Spring Data Access Object 
Java Spring Data Access Object (DAO) is a design pattern that provides an interface to a database or other persistence system. The Java Spring Data Access Object support makes it easier for a developer to work with data access technologies, such as JDBC, JDO, Hibernate, etc. It provides specific data operations without revealing the database details. 

Java Spring DAOalso frees you from the worry of catching exceptions that are specific to each of these persistent technologies. 

Spring JDBC API consists of which classes?
 The following classes are present in the JDBC API: 

  • JdbcTemplate 
  • SimpleJdbcTemplate 
  • NamedParameterJdbcTemplate 
  • SimpleJdbcInsert 
  • SimpleJdbcCall 

 

List down advantages of JdbcTemplate class in Java Spring 
Advantages of the JDBCTemplate class are: 

  • The Spring JdbcTemplate gives the provision to clean-up the resources automatically. Thus the programmer doesn’t have to write additional code.
  • It converts the standard JDBC SqlExceptions into RuntimeExceptions thereby enabling coders to react proactively to the errors. And it also converts predefined vendor-specific error messages to be more readable. 
  • It offers several methods to query the database e.g queryForList() that makes coding easier.  
  • It can directly convert the SQL results into an object or a list of objects by using ResultSetExtractor or RowMapper. 

Java Spring Aspect-Oriented Programming (AOP) Interview Questions  

What is Java Spring Aspect-Oriented Programming?

 Java Spring Aspect-Oriented programming(AOP) is a programming methodology that uses aspects. It breaks down code into smaller modules, known as modularisation, where the aspect is the key unit of modularity. By implementing aspects through Java Spring Aspect-Oriented programming, the programmer can implement crosscutting concerns like logging, transaction management, etc, without affecting the core code and its functionality.  

What are various types of Advice in Spring AOP ?

There are five types of Advice in Spring:  

  • Before: The Advice denoted by @Before runs before the method execution. 
  • After: Denoted by @After, this advice runs after the method execution irrespective of the method outcome. 
  • After Returning: If the method is successfully executed without a runtime exception, then the application runs this advice. 
  • Around: The @Around is the strongest advice as it wraps around and runs before and after the advised method. This type of advice is mostly beneficial in scenarios that require frequent access to a method or database, e.g. caching. 
  • After Throwing: The application runs this advice after the method throws a Runtime Exception.  

Describe what you understand by the Java Spring Model View Controller framework?

Java Spring Model View Controller is a Java framework that creates web applications through the MVC design pattern. Java Spring MVC framework implements the core features of the Spring such as Inversion of Control and Dependency Injection. It uses the DispatcherServlet class to build an MVC application in Java Spring. This class receives incoming requests and maps it to the appropriate resources like controllers, models, etc. 

Java-Spring-framework-Model-View-Controller
Credit: Javatpoint

Components of Java Spring Model View Controller: 

  • Model – A model contains data, i.e, a single object, or multiple objects, for an application.  
  • Controller – A controller consists of the business logic of an application. The annotation @Controller marks a class as a Controller. View – A view can present the information in a specified format, like, JSP+JSTL.   
  • Front Controller – The DispatcherServlet class acts as the front controller and manages the flow of the Spring MVC application. 

What are some benefits of the Java Spring MVC framework?

Below are the advantages of Spring MVC framework in Java: 

  • Separate roles – Separate roles maintained by Spring MVC through specialized objects.  
  • Light-weight – Uses a light-weight servlet container for developing and deploying applications. 
  • Powerful configuration – Robust configuration provided for both framework and application classes.  
  • Rapid development – Facilitates parallel and faster application development. 
  • Reusable business code – Provision of using the existing business objects thereby reducing rework. 
  • Easy to test – Easily testable through JavaBeans that injects the test data via the setter methods. 
  • Flexible Mapping – Specific annotations provided for easy page redirects. 

What is DispatcherServlet in the Spring MVC framework?

java-spring-framework-dispatcherservlet
Credit: Tutorialspoint

DispatcherServlet acts as a front controller for Spring Model View Controller based web applications. It provides a request processing mechanism and handles all HTTP requests and responses. The configurable and delegatable components perform the real work. It extends from javax.servlet.http.HttpServlet class. The web.xml file configures the DispatcherServlet. 

A single web application can define multiple DispatcherServlet instances. Each servlet instance will operate in its namespace, load the application context with mappings, handlers, etc.  DispatcherServlet makes use of Spring configuration classes to find out the delegate components it needs for various operations like request mapping, view resolution, exception handling.

What is the Controller in the Java Spring Model View Controller?

 In Spring Model View Controller, the Controller class handles the incoming client requests. They provide access to application behavior, which is generally a service interface. Controllers interpret the user input, convert it into a model, and represent it as a view to the user. Spring enables the developers to create varied controllers that too abstractly. 

HACKERBUCK AWARDED