50 Best Spring Interview Questions to Ace Your Upcoming Interview Round

50 Best Spring Interview Questions to Ace Your Upcoming Interview Round

Want to find out more about how to write Spring code and get a job using Spring? You're in the right place! This post will tell you what you need to

Play this article

Spring is one of the most popular tools for building web applications in Java EE. Dependency Injection and Aspect-Oriented Programming are at the core of the Spring framework. With good Spring Framework skills, the chances of getting selected in Java interviews are high.

So, to help your interview journey, we have compiled a list of some of the most-asked Spring Interview Questions for experienced and beginners.

Spring Interview Questions & Answers

1) What is Spring Framework?

The Spring Framework is a powerful enterprise-level, lightweight, open-source, loosely coupled application framework meant to reduce the complexity of enterprise-level development. Spring is also called "the framework of frameworks" because it offers support to various important frameworks, such as JSF, Hibernate, Structs, EJB, etc.

Around 20 modules are categorized into the following types:

  • AOP (Aspect Oriented Programming)
  • Web
  • Instrumentation
  • Core Container
  • Test
  • Messaging
  • Data Access/Integration

For beginners, the best Spring tutorials are the most reliable way to understand the Spring framework in detail.

2) What are the features of Spring Framework?

  • The Spring framework follows a layer-based architecture that assists in selecting the appropriate components and provides a robust and cohesive framework for the development of J2EE applications.
  • AOP (Aspect Oriented Programming) in Spring enables unified development by ensuring that the application's business logic is separated from other system services.
  • Spring provides a highly configurable MVC web application framework that can switch to other frameworks easily.
  • The application provides the creation and management of configurations, as well as lifecycle management of applications.
  • Spring has a unique design principle known as IoC (Inversion of Control) that provides objects with their dependencies rather than searching for creating dependent objects.
  • The Spring Framework is a lightweight, Java-based, loosely coupled framework.
  • Spring provides a generic abstraction layer for transaction management that's also useful in containerless environments.
  • Spring provides a convenient API that translates technology-specific exceptions (thrown by JDBC, Hibernate, or other frameworks) into consistent, unchecked exceptions. As a result, it introduces abstraction and greatly simplifies exception handling.

3) What is the advantage of using Spring Framework?

Spring Framework has the following advantages:

  • It reduces direct dependencies between the application's various components. The Spring IoC container is responsible for initializing resources or beans and injecting them as dependencies.
  • Writing unit test cases for the Spring framework is straightforward. We can efficiently write a test configuration and inject our mock beans for testing.
  • It reduces the amount of boiler-plate code, such as initializing objects and opening/closing resources.
  • The spring framework is divided into modules, which helps us keep our applications lightweight.
  • Spring framework supports most of the Java EE features along with many more.

4) What is a Spring configuration file?

A Spring configuration file is an XML file that essentially contains the class information and describes how those classes are configured and linked together. XML configuration files are more verbose and cleaner.

5) What do you mean by IoC (Inversion of Control) Container?

Spring container forms the core of the Spring Framework. The Spring container uses Dependency Injection (DI) to manage the application components by creating objects, configuring them, and managing their overall lifecycles. Spring containers can be instructed to do tasks either by XML configuration, Java annotations, or Java code.

6) Explain the difference between constructor and setter injection?

  • The partial injection is not allowed in constructor injection, but it is allowed in setter injection.
  • Construction injection does not override setter properties, but the opposite is true for setter injection.
  • When any modification is made, constructor injection creates a new instance. Setter injection does not allow the creation of new instances.
  • When a bean has many properties, constructor injection is recommended. If it has few properties, then setter injection is preferred.

7) What are Spring Beans?

They form the core of the user's application and are controlled by the Spring IoC container. An IoC container instantiates, configures, wires, and manages spring beans. The beans are created based on the configuration metadata supplied by the users (via XML or java annotation configurations).

8) How is the configuration metadata provided to the spring container?

Configuration metadata can be provided in three ways. Here they are:

  • XML-Based Configuration: Bean configurations are specified in XML configuration files along with their dependencies. This starts with a bean tag as shown below:
<bean id="interviewBitBean" 
<property name="name" value="InterviewBit"></property>
  • Annotation-Based configuration: Instead of using XML, beans can be configured into the component classes themselves by adding annotations to the relevant class, method, or field declaration.

By default, annotation wiring is not active in the Spring container. It must be enabled in the Spring XML configuration file as shown below

<!-- bean definitions go here -->
  • Java-based configuration: Spring Framework introduced key functionality for Java configurations. This makes use of the @ Configuration annotated classes and @ Bean annotated methods. Note that:

@ Bean annotation has the same role as the < bean/ > element.

Classes annotated with @ Configuration allow defining inter-bean dependencies by simply calling other @ Bean methods in the same class.

9) What are the bean scopes available in Spring?

There are five scope supports in the Spring Framework. Here they are:

  • Singleton: When using this, the bean definition would be specific to a single instance per IoC container.
  • Prototype: Here, a single bean definition can include any number of object instances.
  • Request: This bean definition is for an HTTP request.
  • Session: In this case, the scope of the bean definition is HTTP-session.
  • Global-session: The scope of this bean definition is a Global HTTP session.

Note: The last three scopes are available only to web-aware ApplicationContext container users.

10) What is auto wiring and name the different modes of it?

Relationships between application beans are automatically wired by the IoC container. Through its BeanFactory, Spring allows collaborators to understand which beans need to be wired automatically. It can be done in several ways, including:

  • no: In this case, there will be no autowiring, and it is the default setting. Wiring should be done using an explicit bean reference.
  • byName: Bean dependencies are injected according to the name of the bean. According to the configuration, it matches and wires its properties to the beans with the same names.
  • byType: Injects the bean dependency based on the type.
  • constructor: In this case, it injects the bean dependency by calling the constructor of the class. The model has a large number of parameters.
  • autodetect: First, the container tries to wire using autowire by the constructor, if that fails then it attempts to wire by byType.

11) What are the limitations of auto wiring?

  • Overriding possibility: Dependencies are specified as constructor arguments (< constructor-arg >) and properties settings (< property >), which override autowiring.

  • Data types restriction: Strings, primitive data types, and classes cannot be autowired.

12) Explain the Bean life cycle in Spring Bean Factory Container.

Following is the life cycle of a bean:

  • An IoC container instantiates the bean according to its definition in an XML file.
  • After that, Spring populates all the properties based on the dependency injection specified in the bean definition.
  • Bean factory containers call setBeanName(), which takes the bean ID, and the corresponding bean must implement the BeanNameAware interface.
  • After that, the factory calls setBeanFactory() by passing an instance of itself (if the BeanFactoryAware interface is implemented in the bean).
  • The preProcessBeforeInitialization() methods are invoked if BeanPostProcessors are associated with the bean.
  • If an init-method is specified, then it will be called.
  • Lastly, postProcessAfterInitialization() methods will be called if there are BeanPostProcessors associated with the bean that needs to be run after creation.

13) What do you understand by the term 'Spring Boot'?

Spring Boot is an open-source, java-based framework that provides support for Rapid Application Development and gives a platform for developing stand-alone and production-ready spring applications with the need for very few configurations.

14) What are the features of Spring Boot?

  • Spring Boot CLI – You can use Groovy or Maven for writing Spring Boot applications and avoid boilerplate code.
  • Starter Dependency – Through this feature, Spring Boot aggregates common dependencies together and eventually improves productivity and reduces workload.
  • Spring Initializer – This is a web application that helps a developer in creating an internal project structure. This feature allows developers to use the feature without manually setting up the project structure.
  • Auto-Configuration – This feature allows you to load the default configuration according to the project you are working on. By doing so, unnecessary WAR files can be avoided.
  • Spring Actuator – Spring Boot is accompanied by an actuator that provides "Management EndPoints" which helps the developer to view the internals and metrics of the application.
  • Logging and Security – It ensures that all applications built with Spring Boot are correctly secured without hassles.

15) Differentiate between Spring and Spring Boot.

While the Spring Framework provides several useful features such as dependency injection, data binding, aspect-oriented programming (AOP), data access, and more, Spring Boot simplifies the use of the Spring Framework by simplifying or managing various loosely coupled blocks of Spring that are tedious and at times can cause chaos.

Spring boot simplifies commonly used spring dependencies and allows you to run applications straight from the command line. Furthermore, it doesn't require an application container, and it helps to monitor several components and configure them externally.

16) Explain the advantages of using Spring Boot for application development.

Following are the advantages of using Spring Boot for application development:

  • By using Spring Boot, standalone applications can be created that can be started using java.jar (No need to configure WAR files).
  • Furthermore, Spring Boot offers 'started' POMs for Maven configuration.
  • Undertow, Tomcat, Jetty or other web servers can be embedded directly.
  • Auto-Configuration: Automatically configures an application based on the classpath's dependencies.
  • Spring Boot was developed to reduce the lines of code.
  • Applications developed using spring boot have an easier time launching and offer production-ready support.

17) What is Spring WebFlux?

Spring 5 introduced a new module, Spring WebFlux. Spring WebFlux is the alternative to the Spring MVC module. It is used to create a fully asynchronous and non-blocking application based on the event-loop execution model.

18) What are the benefits of using Spring Tool Suite?

In Eclipse, we can install plugins to access all of Spring Tool Suite's features. While STS is available with Eclipse, it includes other important things such as Maven support, templates for creating Spring projects, and a TC server to enhance the performance of Spring applications.

19) What do you understand by Dependency Injection?

Using Dependency Injection design patterns, we can easily remove hard-coded dependencies from our applications and make them extensible, maintainable, and extendable. We can use the dependency injection pattern to move dependency resolution from compile-time to run-time.

Separation of Concerns, Boilerplate Code Reduction, Configurable Components, and Easy Unit Testing are some benefits of using Dependency Injection.

20) How do we implement DI in Spring Framework?

DI (Dependency Injection) in spring applications can be implemented using Spring XML-based and Annotation-based configuration.

21) Name some of the important Spring Modules?

The following are some of the most important Spring Framework modules:

  • Spring Web Module – for creating web applications.
  • Spring Context – for dependency injection.
  • Spring DAO – for database operations using DAO pattern.
  • Spring MVC – Model-View-Controller implementation for creating web applications, web services, etc.
  • Spring ORM – for ORM tools support such as Hibernate.
  • Spring AOP – for aspect-oriented programming.
  • Spring JDBC – for JDBC and DataSource support.

22) What do you understand by Aspect-Oriented Programming?

There are a few crosscutting concerns shared by enterprise applications that apply to different types of Objects and application modules, such as logging, transaction management, data validation, and authentication. Object-oriented programming achieves modularity by using classes. The modularity of AOP is achieved by using Aspects, which are configured to cut across different class methods.

Using AOP, you eliminate cross-cutting tasks from classes, which would otherwise be impossible under a conventional object-oriented approach. For instance, we can have a separate class for logging but the other classes will have to call these methods. In AOP, however, aspects are configured and methods are executed automatically.

23) What are the important features of Spring 5?

Spring 5 takes a big step forward from Spring 4. The following are some of the key features:

  • Support for Kotlin, Lombok, Reactor 3.1 Flux, and Mono as well as RxJava.
  • Support for Java 8 and higher versions, so we can use lambda expressions.
  • Spring WebFlux that brings reactive programming to Spring.
  • Support for Java EE7 and Servlet 4.0 specs.
  • Support for JUnit 5
  • Implemented spring-JCL to streamline logging, which earlier was a mess due to the lack of a single point of logging.
  • Support for providing spring components information via index file “META-INF/spring.components” instead of classpath scanning.
  • File operations are now performed via NIO 2 streams, which is a huge improvement if your app handles a lot of files.

24) What is Aspect, Advice, Pointcut, JointPoint, and Advice Arguments in AOP?

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

Advice: Advice is the action taken at a certain join point. These methods are executed by the application when a specific pointcut with a matching join point is reached. It can be thought of as an interceptor for Spring or a servlet filter.

Pointcut: Pointcuts are regular expressions that are matched against join points to determine whether advice should be executed or not. There are different types of expressions that Pointcut uses to match the join points. For determining the join points where advice methods will be applied, the Spring framework uses the AspectJ pointcut expression language.

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

Advice Arguments: In the advice methods, we can pass arguments. The args() expression in the pointcut can be applied to any method matching the argument pattern. Using this method, we need to use the same name in the advice method, which determines the argument type.

25) What is the importance of the Spring bean configuration file?

To define all the beans that will be initialized by Spring Context, we use the Spring Bean configuration file. When we create a Spring ApplicationContext instance, it reads the spring bean XML file and initializes all of them. When the context is initialized, we can use it to get different bean instances.

Along with Spring Beans, this file contains Spring MVC interceptors, view resolvers, and other annotation-based configuration elements.

26) What is the difference between Spring AOP and AspectJ AOP?

Object-Oriented Programming is implemented by AspectJ, whereas Spring implements AOP for some cases. These are the main differences between Spring AOP and AspectJ:

  • Spring AOP is easier to use than AspectJ since we don't need to worry about weaving.
  • AspectJ annotations are supported by Spring AOP, so you can work with Spring AOP if you are familiar with AspectJ.
  • Since Spring AOP only supports proxy-based AOP, it can be applied only to method execution join points. AspectJ supports all types of pointcuts.
  • Spring AOP has the limitation that it can be applied only to beans created through Spring Context.

27) What is Bean wiring and @ Autowired annotation?

Spring Bean Wiring is the process of injecting spring bean dependencies during initialization. Generally, it's best practice to wire up all beans explicitly, but the spring framework also supports autowiring.

The @ Autowired annotation can be used with fields or methods for autowiring byType. For this annotation to work, we also have to enable annotation-based configuration in the spring bean configuration file. This can be done by context:annotation-config element.

28) Does Spring Bean provide thread-safety?

By default, the scope of Spring beans is singleton, so there will be only one instance per context. Thus, having a class-level variable that any thread can update will result in inconsistent data. Therefore, spring beans are not thread-safe in default mode.

You can, however, change the scope for spring beans to request, prototype, or session to achieve thread safety at the expense of performance. It is a design decision based on the project requirements.

29) What is a Controller in Spring MVC?

As with the MVC design pattern, the Controller class handles all client requests and sends them to the configured resources. DispatcherServlet is the Spring MVC front controller that initializes the context based on the bean configurations.

A Controller class is responsible for handling different types of client requests based on the request mappings. Using the @ Controller annotation, we can create a controller class. Typically, it is used with the @ RequestMapping annotation to define handler methods for specific URI mapping.

30) What is DispatcherServlet and ContextLoaderListener?

DispatcherServlet is the Spring MVC front controller that initializes the context based on the bean configurations. Furthermore, it will scan the packages and configure any bean that contains annotations such as @ Component, @ Controller, @ Repository, or @ Service.

ContextLoaderListener starts and shuts down Spring's root WebApplicationContext. Among its most important functions are tying the lifecycle of ApplicationContext with the lifecycle of ServletContext and automating the creation of ApplicationContext. It can be used to define shared beans that can be used in various spring contexts.

31) What is ViewResolver in Spring?

Using ViewResolver implementations, view pages are resolved by name. It is configured in the spring bean configuration file. For example:

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />

32) How to handle exceptions in Spring MVC Framework?

To achieve robust exception handling, Spring MVC Framework provides the following methods.

  • Controller-Based – In controller-based systems, we can specify exception handling methods in the controller classes. These methods only need to be annotated with @ ExceptionHandler.

  • Global Exception Handler – Handling exceptions is a cross-cutting concern, and Spring provides @ ControllerAdvice annotation that we can use with any class to implement our global exception handling.

  • HandlerExceptionResolver implementation – For generic exceptions, it serves static pages most of the time. HandlerExceptionResolver is an interface in Spring Framework that we can implement to create a global exception handler. As another way to define the global exception handler, the Spring framework provides default implementation classes that we can define in our spring bean configuration file to benefit from the spring framework exception handling.

33) What are the minimum configurations needed to create a Spring MVC application?

Following are the steps necessary for creating a simple Spring MVC application.

  • Add spring-context and spring-webmvc dependencies to the project.
  • Set up DispatcherServlet in the web.xml file to handle requests through the spring container.
  • A spring bean configuration file is required to define the beans and if annotations are being used, then it must be configured here. We also need to configure the view resolver for view pages.
  • Client requests are handled by request mappings defined in a controller class.

Using these steps, you should be able to create an easy Spring MVC Hello World application.

34) What is a View Resolver pattern and explain its significance in Spring MVC?

View Resolver pattern is a J2EE pattern that allows the applications to dynamically choose technology for rendering the data on the browser (View). HTML, JSP, XSLT, JSF, or any other such technology can be used as a View.

View Resolver contains information about different views. The controller returns the name of the View, which is passed to the View Resolver by the DispatcherServlet for selection of the appropriate View technology, and then the data is displayed. Spring MVC's default ViewResolver is InternalResourceViewResolver.

35) Can you create a controller without using @ Controller or @ RestController annotations?

Definitely! It is possible to create a controller without using the @ Controller or @ RestController annotations by annotating the Spring MVC Controller classes with the @ Component annotation. With this example, the @ RequestMapping annotation does the actual mapping of the request to the handler method.

36) Can we send an Object as the response of the Controller handler method?

We can do so by using the @ ResponseBody annotation. We use this method for sending JSON or XML-based responses in restful web services.

37) How to validate form data in Spring Web MVC Framework?

Spring supports JSR-303 annotation-based validation and provides us with a Validator interface through which we can create our validators. We need to annotate bean variables with the required validations to use JSR-303 based validation.

38) How to upload files in the Spring MVC Application?

The MultipartResolver interface implementation in Spring provides support for uploading files. It is very easy to use and requires only configuration changes to work. To handle the incoming file and process it, we would need to write a controller method.

39) What is Spring MVC Interceptor and how to use it?

Spring MVC Interceptors are like Servlet Filters and allow us to intercept and process client requests. Client requests can be intercepted in three places - preHandle, postHandle, and afterCompletion.

Spring interceptors can be created by implementing the HandlerInterceptor interface or by extending the abstract class HandlerInterceptorAdapter.

In the spring bean configuration file, interceptors must be configured. In addition, we can configure an interceptor for specific URI mappings as well or intercept all client requests.

40) What is Spring Security?

The Spring security framework provides both authentication and authorization in Java applications. Furthermore, it takes care of many common security vulnerabilities, such as CSRF attacks.

By using annotations such as @ EnableWebSecurity, it is easy and beneficial to use Spring security in web applications.

41) What is the Spring JdbcTemplate class and how to use it?

The Spring JdbcTemplate provides an easy way to connect to a database and run SQL queries. Even though it uses JDBC api internally, it eliminates a lot of issues with JDBC API. We can use the Jdbc template utility class to avoid boiler-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement, etc.

42) How to use Tomcat JNDI DataSource in Spring Web Application?

To use the servlet container configured JNDI DataSource, it must be configured in the spring bean configuration file and then injected into spring beans as dependencies. After that, we can use JdbcTemplate to perform database operations.

<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>

43) What is Hibernate ORM Framework?

Mapping application domain model objects to relational database tables is known as object-relational mapping (ORM). Hibernate is the most popular Java-based ORM framework.

44) What is Hibernate Validator Framework?

The Hibernate Validator Framework allows you to express and validate application constraints. By default, metadata are annotations, with the ability to override and extend through XML. It is not dependent on a specific application tier or programming model and is available for both server-side and client-side applications.

45) What are some of the classes for Spring JDBC API?

Here are some of the classes for Spring JDBC API:

  • NamedParameterJdbcTemplate
  • SimpleJdbcCall
  • SimpleJdbcInsert
  • JdbcTemplate
  • SimpleJdbcTemplate

46) What is Spring AOP Proxy pattern?

The proxy pattern is a well-used design pattern in which a proxy is an object that looks like another object, but has special functionality behind the scenes. With Spring AOP, proxies are used to implement aspect contracts in runtime using the AOP framework.

The standard JDK dynamic proxies are default AOP proxies that enable any interface(s) to be proxied. The Spring AOP package can also use CGLIB proxies rather than interfaces for proxying classes. If a business object does not implement an interface, then CGLIB proxies are used by default.

47) What is Spring DAO?

The Spring DAO (Data Access Object) is an object which provides an abstract interface for JDBC implementation frameworks. With the help of a series of Support classes, Spring DAO can access JDBC, Hibernate, MyBatis, JPA, and JDO. Moreover, it supports a generalized exception hierarchy by defining a @ Repository annotation.

Using this annotation we define a Spring container that will translate SQLException into Spring's data access strategy-independent DataAccessException hierarchy.

48) What are the AOP terminology?

The following are AOP terminologies or concepts:

  • Weaving
  • Target Object
  • JoinPoint
  • Pointcut
  • Advice
  • Interceptor
  • AOP Proxy
  • Introduction
  • Aspect

49) How can you fetch records by spring JdbcTemplate?

By using the query method of JdbcTemplate, you can retrieve records from the database. There are two ways to do this:

  • ResultSetExtractor
  • RowMapper

50) What are the types of IOC containers in spring?

In the spring framework, there are two types of IOC containers.

  1. BeanFactory
  2. ApplicationContext

If you have made it this far, then certainly you are willing to learn more about Java. Here are some more resources related to Java that we think will be useful to you.

Did you find this article valuable?

Support Yash Tiwari by becoming a sponsor. Any amount is appreciated!