Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What will be the selection state of a checkbox input if the user first checks the checkbox and gets validation errors in other fields and then unchecks the checkbox after getting the errors?

Answer»

The validation is generally performed during HTTP POST requests. During HTTP requests, if the state of the checkbox is unchecked, then HTTP includes the request parameter for the checkbox THEREBY not picking up the updated selection. This can be fixed by making use of a hidden form field that starts with _ in the Spring MVC.

Conclusion:

In this article, we have seen the most commonly asked Spring INTERVIEW Questions during an interview. Spring is a very powerful framework that allows building enterprise-level web applications. Applications developed using Spring are generally quick, SCALABLE, and transparent. Due to this, Spring has been embraced by a HUGE Java Developer’s community thereby making it an inevitable part of any Java Developer’s Job Role. Knowing Spring ensures that an added advantage is with the developers to progress steadily in their careers too.

Tip: We also recommend READING guides posted here.

2.

How is it possible to use the Tomcat JNDI DataSource in the Spring applications?

Answer»

To use the servlet container which is CONFIGURED in the JNDI (Java Naming and Directory INTERFACE) DataSource, the DataSource bean has to be configured in the spring bean config file and then injected into the beans as dependencies. Post this, the DataSource bean can be used for performing database operations by means of the JDBCTEMPLATE. The syntax for registering a MySQL DataSource bean:

&LT;bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"&GT; <property name="jndiName" value="java:comp/env/jdbc/MySQLDB"/></bean>
3.

What do you understand by MultipartResolver?

Answer»

The MultipartResolver is used for handling the file upload scenarios in the Spring web application. There are 2 CONCRETE implementations of this in Spring, they are:

  • CommonsMultipartResolver meant for Jakarta Commons FileUpload
  • StandardServletMultipartResolver meant for for SERVLET 3.0 Part API

To implement this, we need to create a bean with id=“multipartResolver” in the application context of DispatcherServlet. Doing this ensures that all the requests handled by the DispatcherServlet have this resolver applied whenever a multipart request is detected. If a multipart request is detected by the DispatcherServlet, it resolves the request by means of the already configured MultipartResolver, and the request is passed on as a wrapped/abstract HttpServletRequest. Controllers then cast this request as the MultipartHttpServletRequest interface to get access to the Multipart files. The following DIAGRAM illustrates the FLOW clearly:

4.

How are i18n and localization supported in Spring MVC?

Answer»

Spring MVC has LOCALERESOLVER that supports i18n and localization. for supporting both internationalization and localization. The following beans need to be configured in the application:

  • SessionLocaleResolver: This bean plays a vital role to get and resolve the locales from the pre-defined attributes in the user session.

Syntax:

<bean id="localeResolver"class="org.Springframework.web.servlet.i18n.SessionLocaleResolver"&GT; <property name="defaultLocale" value="en" /></bean>
  • LocaleChangeInterceptor: This bean is useful to resolve the parameter from the incoming request.

Syntax:

<bean id="localeChangeInterceptor"class="org.Springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang" /></bean>
  • DefaultAnnotationHandlerMapping: This REFERS to the HandlerMapping interface implementation which maps the handlers/interceptors BASED on the HTTP paths specified in the @RequestMapping at type or method level.

Syntax:

<bean class="org.Springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <ref bean="localeChangeInterceptor" /> </list> </property></bean>
5.

Differentiate between a Bean Factory and an Application Context.

Answer»

BeanFactory and the ApplicationContext are both JAVA interfaces. The difference is that the ApplicationContext extends the BeanFactory. BeanFactory provides both IoC and DI BASIC features whereas the ApplicationContext provides more advanced features. Following are the differences between these two:

Category BeanFactoryApplicationContext
Internationalization (i18n)Does not provide support for i18n.Provides support for i18n.
Event PublishingProvides the ability to PUBLISH events to listener beans by USING ContextStartedEvent and ContextStoppedEvent to publish context when it is started and stopped respectively.ApplicationContext supports event handling by means of the ApplicationListener interface and ApplicationEvent class.
ImplementationsXMLBeanFactory is a popular implementation of BeanFactory.ClassPathXmlApplicationContext is a popular implementation of ApplicationContext. Also, Java uses WebApplicationContext that extends the interface and adds getServletContext() method.
AutowiringFor autowiring, beans have to be REGISTERED in the AutoWiredBeanPostProcessor API.Here, XML configuration can be done to achieve autowiring.
6.

How to get ServletConfig and ServletContext objects in spring bean?

Answer»

This can be DONE by either implementing the spring-aware INTERFACES or by using the @Autowired ANNOTATION.

@Autowiredprivate SERVLETCONTEXT servletContext;@Autowiredprivate SERVLETCONFIG servletConfig;
7.

How is the form data validation done in Spring Web MVC Framework?

Answer»

Spring MVC does the task of data validation using the validator object which implements the Validator interface. In the custom validator class that we have created, we can use the utility methods of the ValidationUtils class like rejectIfEmptyOrWhitespace() or rejectIfEmpty() to perform validation of the form FIELDS.

@Componentpublic class UserValidator implements Validator{ public boolean SUPPORTS(Class clazz) { return UserVO.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name", "Name is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "error.age", "Age is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "error.phone", "Phone is required."); }}

In the fields that are subject to validation, in case of errors, the validator methods would create field error and bind that to the field.

To activate the custom validator as spring bean, then:

  • We have to add the @COMPONENT annotation on the custom validator class and initiate the component scanning of the package containing the validator declarations by ADDING the below CHANGE:
<context:component-scan base-package="com.interviewbit.validators"/>

OR

The validator class can be registered in the context file directly as a bean as shown:

<bean id="userValidator" class="com.interviewbit.validators.UserValidator" />
8.

What are the differences between the vs tags?

Answer»

<context:annotation-CONFIG> is used for ACTIVATING applied ANNOTATIONS in pre-registered beans in the application context. It also registers the beans defined in the config file and it scans the annotations within the beans and activates them.

The <context:component-scan> TAG does the task of <context:annotation-config> along with scanning the packages and registering the beans in the application context.

<context:annotation-config> = Scan and activate annotations in pre-registered beans.
<context:component-scan> = Register Bean + Scan and activate annotations in package.

9.

Is there any need to keepspring-mvc.jar on the classpath or is it already present as part of spring-core?

Answer»

The SPRING-mv.jar does not belong to the spring-core. This means that the jar has to be INCLUDED in the project’s classpath if we have to use the Spring MVC framework in our project. For JAVA applications, the spring-mvc.jar is PLACED INSIDE /WEB-INF/lib folder.

10.

What are Spring Interceptors?

Answer»

Spring Interceptors are used to pre-handle and post-handle the web requests in Spring MVC which are handled by Spring Controllers. This can be achieved by the HandlerInterceptor interface. These handlers are used for manipulating the MODEL attributes that are passed to the controllers or the views.
The Spring handler interceptor can be registered for specific URL mappings so that it can intercept only those requests. The custom handler interceptor must implement the HandlerInterceptor interface that has 3 CALLBACK methods that can be implemented:

  • preHandle()
  • postHandle()
  • afterCompletion()

The only PROBLEM with this interface is that all the methods of this interface need to be implemented irrespective of its REQUIREMENTS. This can be avoided if our handler class extends the HandlerInterceptorAdapter class that internally implements the HandlerInterceptor interface and provides default BLANK implementations.

11.

Why do we need BindingResults?

Answer»

BindingResults is an important Spring interface that is within the org.Springframework.validation package. This interface has a very simple and easy process of invocation and plays a vital role in detecting errors in the submitted forms. However, care has to be taken by the developer to USE the BindingResult parameter just after the object that NEEDS validation. For example:

@PostMapping("/interviewbit")public String registerCourse(@Valid RegisterUser registerUser, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { RETURN "home"; } model.addAttribute("message", "Valid inputs"); return "home";}

The Spring will understand to FIND the corresponding VALIDATORS by checking the @Valid annotation on the parameter.

12.

Where does the access to the model from the view come from?

Answer»

The view requires access to the model to render the output as the model contains the REQUIRED data meant for rendering. The model is associated with the controller that PROCESSES the CLIENT REQUESTS and FINALLY encapsulates the response into the Model object.

13.

How does the Spring MVC flow look like? In other words, How does a DispatcherServlet know what Controller needs to be called when there is an incoming request to the Spring MVC?

Answer»

A Dispatcher Servlet knows which controller to call by means of handler mappings. These mappings have the mapping between the controller and the requests. BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping are the two most commonly USED handler mappings.

  • BeanNameUrlHandlerMapping: When the URL request matches the bean name, the class CORRESPONDING to the bean definition is the actual controller that is responsible for processing the request.
  • SimpleUrlHandlerMapping: Here, the mapping is very explicit. The number of URLs can be specified here and each URL is associated explicitly with a controller.

If the Spring MVC is CONFIGURED using annotations, then @RequestMapping annotations are used for this purpose. The @RequestMapping ANNOTATION is configured by making use of the URI path, HTTP METHODS, query parameters, and the HTTP Headers.

14.

How is the root application context in Spring MVC loaded?

Answer»

The ROOT application context is loaded using the ContextLoaderListener that BELONGS to the ENTIRE application. SPRING MVC allows instantiating multiple DispatcherServlet and each of them have multiple contexts specific to them. They can have the same root context too.

15.

How is the dispatcher servlet instantiated?

Answer»

The dispatcher servlet is instantiated by means of servlet containers such as Tomcat. The Dispatcher Servlet should be defined in web.xml The DispatcherServlet is instantiated by Servlet containers like Tomcat. The Dispatcher Servlet can be defined in web.xml as shown below:

&LT;?xml VERSION="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Define Dispatcher Servlet --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>InterviewBitServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>

Here, the load-on-startup tag is 1 which indicates that the DispatcherServlet is instantiated whenever the Spring MVC APPLICATION to the servlet container. During this PROCESS, it looks for the servlet-name-context.xml file and initializes BEANS that are defined in the file.

16.

What is the significance of @Repository annotation?

Answer»

@Repository annotation indicates that a COMPONENT is USED as the repository that ACTS as a means to store, SEARCH or retrieve data. These can be added to the DAO classes.

17.

How can you achieve thread-safety in beans?

Answer»

The thread safety can be ACHIEVED by changing the scope of the bean to REQUEST, session or PROTOTYPE but at the COST of performance. This is purely based on the project REQUIREMENTS.

18.

Are singleton beans thread-safe?

Answer»

No, the singleton beans are not thread-safe because the concept of thread-SAFETY essentially deals with the EXECUTION of the program and the singleton is simply a design pattern MEANT for the creation of OBJECTS. Thread safety nature of a BEAN depends on the nature of its implementation.

19.

Differentiate between the @Autowired and the @Inject annotations.

Answer»
@Autowired@Inject
This annotation is part of the Spring framework.This annotation is part of Java CDI.
Has required attribute.Does not have the required attribute.
Singleton is the default scope for autowired beans.Prototype is the default scope of inject beans.
In case of ambiguity, then @Qualifier annotation is to be used.In case of ambiguity, then @NAMED qualifier needs to be used.
Since this annotation is provided by the Spring framework, in case you shift to another Dependency injection framework, there WOULD be a LOT of refactoring needed.Since this annotation is part of Java CDI, it is not framework dependent and hence LESS code refactoring when there are framework CHANGES.
20.

What is the importance of @Required annotation?

Answer»

The annotation is used for indicating that the property of the bean should be populated via autowiring or any explicit value during the bean definition at the CONFIGURATION time. For example, consider a code snippet below where we NEED to have the values of age and the name:

import org.Springframework.beans.factory.annotation.Required;PUBLIC class USER { private INT age; private String name; @Required public void setAge(int age) { this.age = age; } public Integer getAge() { return this.age; } @Required public void setName(String name) { this.name = name; } public String getName() { return this.name; }}
21.

What is the importance of session scope?

Answer»

Session scopes are used to create BEAN INSTANCES for HTTP sessions. This would mean that a single bean can be used for serving multiple HTTP REQUESTS. The scope of the bean can be defined by means of using scope attribute or using @Scope or @SessionScope annotations.

  • Using scope attribute:
<bean id="userBean" CLASS="com.interviewbit.UserBean" scope="session"/>
  • Using @Scope annotation:
@Component@Scope("session")public class UserBean { //some methods and properties}
  • Using @SessionScope:
@Component@SessionScopepublic class UserBean { //some methods and properties}
22.

What are the types of Spring MVC Dependency Injection?

Answer»

There are two types of DI (Dependency Injection):

  • Construction-Based:
    • This TYPE of DI is accomplished when the Spring IoC (Inversion of Control) container invokes parameterized constructor having a dependency on other classes.
    • This cannot instantiate the values partially and ensures that the dependency injection is done fully.
    • There are two possible ways of achieving this:

Annotation Configuration: This approach USES POJO objects and annotations for configuration. For example, consider the below code snippet:

@Configuration@ComponentScan("com.interviewbit.constructordi")public class SpringAppConfig { @Bean public Shape shapes() { return new Shapes("Rectangle"); } @Bean public Dimension dimensions() { return new Dimension(4,3); }}

Here, the annotations are used for notifying the Spring runtime that the class specified with @Bean annotation is the provider of beans and the process of context scan needs to be performed on the package com.interviewbit.constructordi by means of @ComponentScan annotation. Next, we will be defining a Figure class component as below:

@Componentpublic class Figure { private Shape shape; private Dimension dimension; @Autowired public Figure(Shape shape, Dimension dimension) { this.shape = shape; this.dimension = dimension; }}

Spring encounters this Figure class while performing context scan and it initializes the instance of this class by invoking the constructor annotated with @Autowired. The Shape and Dimension instances are obtained by calling the methods annotated with @Bean in the SpringAppConfig class. Instances of Engine and Transmission will be obtained by calling @Bean annotated methods of the Config class. Finally, we need to bootstrap an ApplicationContext using our POJO configuration:

ApplicationContext context = new AnnotationConfigApplicationContext(SpringAppConfig.class);Figure figure = context.getBean(Figure.class);

XML Configuration: This is another way of configuring Spring runtime by using the XML configuration file. For example, consider the below code snippet in the springAppConfig.xml file:

<bean id="toyota" class="com.interviewbit.constructordi.Figure"> <constructor-arg index="0" ref="shape"/> <constructor-arg index="1" ref="dimension"/></bean><bean id="shape" class="com.interviewbit.constructordi.Shape"> <constructor-arg index="0" value="Rectangle"/></bean><bean id="dimension" class="com.interviewbit.constructordi.Dimension"> <constructor-arg index="0" value="4"/> <constructor-arg index="1" value="3"/></bean>

The constructor-arg tag can accept either literal value or another bean’s REFERENCE and explicit index and type. The index and type arguments are used for resolving conflicts in cases of ambiguity.
While bootstrapping this class, the Spring ApplicationContext needs to use ClassPathXmlApplicationContext as shown below:

ApplicationContext context = new ClassPathXmlApplicationContext("springAppConfig.xml");Figure figure = context.getBean(Figure.class);
  • Setter-Based:
    • This form of DI is achieved when the Spring IoC container calls the bean’s setter method after a non-parameterized constructor is called to PERFORM bean instantiation.
    • It is possible to achieve circular dependency using setter injection.
    • For achieving this type of DI, we need to configure it through the configuration file under the <property> tag. For example, consider a class InterviewBit that sets the property articles as shown below:
package com.interviewbit.model;import com.interviewbit.model.Article;public class InterviewBit { // Object of the Article interface Article article; public void setArticle(Article article) { this.article = article; }}

In the bean configuration file, we will be setting as below: 

<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-2.5.xsd"> <bean id="InterviewBit" class="com.interviewbit.model.InterviewBit"> <property name="article"> <ref bean="JsonArticle" /> </property> </bean> <bean id="JsonArticle" class="com.interviewbit.bean.JsonArticle" /></beans>

The ‘JsonArticle’ bean is injected into the InterviewBit class object by means of the setArticle method.
In cases where both types of dependencies are used, then the setter dependency injection has more preference by considering the specificity nature.

23.

What is the importance of the web.xml in Spring MVC?

Answer»

web.xml is also KNOWN as the Deployment Descriptor which has DEFINITIONS of the servlets and their mappings, filters, and lifecycle listeners. It is also USED for configuring the ContextLoaderListener. Whenever the application is DEPLOYED, a ContextLoaderListener instance is created by Servlet container which leads to a load of WEBAPPLICATIONCONTEXT.

24.

What is the role of @ModelAttribute annotation?

Answer»

The annotation plays a very important role in binding method parameters to the respective attribute that corresponds to a model. Then it REFLECTS the same on the presentation page. The role of the annotation ALSO depends on what the developer is USING that for. In case, it is used at the method level, then that method is RESPONSIBLE for adding attributes to it. When used at a parameter level, it represents that the parameter value is MEANT to be retrieved from the model layer.

25.

What is the use of @Autowired annotation?

Answer»

@Autowired annotation is meant for the injection of a bean by MEANS of its type along with methods and FIELDS. This helps the Spring framework to resolve dependencies by injecting and COLLABORATING the BEANS into another bean. For example, consider the below code snippet:

import org.Springframework.beans.factory.annotation.Autowired;import java.util.*;public class InterviewBit { // Autowiring/Injecting FormatterUtil as dependency to InterviewBit class @Autowired private FormatterUtil formatterUtil; public Date something( String value ){ Date dateFormatted = formatterUtil.formatDate(value); RETURN dateFormatted }}/*** Util class to format any string value to valid date format*/public class FormatterUtil { public Date formatDate(String value){ //code to format date }}
26.

What is the Model in Spring MVC?

Answer»
  • Model is a reference to have the data for rendering.
  • It is always created and PASSED to the view in Spring MVC. If a mapped controller METHOD has Model as a parameter, then that model instance is automatically injected to that method.
  • Any ATTRIBUTES set on the injected model WOULD be PRESERVED and passed to the View.
27.

What are the differences between @RequestParam and @PathVariable annotations?

Answer»
  • Even though both these annotations are used to EXTRACT some DATA from URL, there is a key difference between them.
    • The @RequestParam is used to extract query parameters that is ANYTHING after “?” in the URL.
    • The @PathVariable is used to extract the data present as part of the URI itself.]
    • For example, if the given URL is http://localhost:8080/InterviewBit/Spring/SpringMVC/?format=json, then you can access the query parameter “format” using the @RequestParam annotation and /Spring/{type} using the @PathVariable, which will give you SpringMVC.
@RequestMapping("/Spring/{type}")public void getQuestions(@PathVariable("type") STRING type, @RequestParam(value = "format", required = false) String format){ /* Some code */}
28.

What is ContextLoaderListener and what does it do?

Answer»
  • The CONTEXTLOADERLISTENER loads and creates the ApplicationContext, so a developer need not write explicit code to do CREATE it. In short, it is a listener that aids to bootstrap Spring MVC.
    • The application context is where Spring bean resides. For a web application, there is a subclass called WebAppliationContext.
  • The lifecycle of the ApplicationContext is tied to the lifecycle of the ServletContext by USING ContextLoaderListener. The ServletContext from the WebApplicationContext can be obtained using the getServletContext() METHOD.
29.

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

Answer»
  • Yes! You can create a CONTROLLER without @Controller or @RestController annotations by annotating the SPRING MVC Controller classes USING the @COMPONENT annotation. In this case, the real job of request MAPPING to handler method is done using the @RequestMapping annotation.
30.

What is the @Controller annotation used for?

Answer»
31.

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

Answer»
  • It is a J2EE pattern that ALLOWS the APPLICATIONS to dynamically choose technology for rendering the data on the browser (View).
    • Any technology like HTML, JSP, XSLT, JSF, or any other such technology can be used as View.
  • The View Resolver has the information of different views. The CONTROLLER returns the name of the View which is then passed to View Resolver by the DispatcherServlet for selecting the APPROPRIATE View technology and then the data is displayed.
  • The default ViewResolver used in Spring MVC is InternalResourceViewResolver.
32.

What is DispatcherServlet in Spring MVC? In other words, can you explain the Spring MVC architecture?

Answer»

Spring MVC framework is built around a central servlet CALLED DispatcherServlet that handles all the HTTP requests and responses. The DispatcherServlet does a lot more than that:

  • It seamlessly integrates with the IOC container and allows you to use each feature of Spring in an easier manner.
  • The DispatcherServlet CONTACTS HandlerMapping to call the APPROPRIATE Controller for processing the request on receiving it. Then, the controller calls appropriate service methods to set or process the Model data. The service processes the data and returns the view name to DispatcherServlet. DispatcherServlet then takes the HELP of ViewResolver and picks up the defined view for the request. Once the view is decided, the DispatcherServlet passes the Model data to View where it is finally rendered on the browser.
33.

What are the benefits of Spring MVC framework over other MVC frameworks?

Answer»
  • Clear separation of roles – There is a specialised dedicated object for EVERY role.
  • Reusable BUSINESS code logic – With Spring MVC, there is no NEED for duplicating the code. Existing objects can be USED as commands instead of replicating them in order to extend a particular framework base class.
  • Spring MVC framework provides customizable binding and validation.
  • Also provides customizable locale and theme resolution.
  • Spring MVC supports customizable handler mapping and view resolution too.
34.

What is the Spring MVC framework?

Answer»
  • Spring MVC is REQUEST driven framework and ONE of the core components of the Spring framework.
  • It COMES with ready to use loosely coupled components and elements that greatly aids developers in building flexible and robust web applications.
  • The MVC (Model - View - Controller) architecture separates and PROVIDES loose coupling between the DIFFERENT aspects of the application – input logic (Model), business logic (Controller), and UI logic (View).