Try   HackMD

Spring MVC Interview Questions

Introduction

The Spring Framework was first developed by Rod Johnson in 2003. It was developed to make the development of Java applications quicker, easier and safer for developer. Spring Framework is an open-source, lightweight, easy to build a framework that can also be considered as a framework of frameworks as it houses various frameworks like Dependency Injection, Spring MVC, Spring JDBC, Spring Hibernate, Spring AOP, EJB, JSF etc. A key element of Spring is the feature of application's infrastructural support. Spring focuses on providing the "plumbing" of enterprise-level applications and ensures that the developers can focus purely on application-level business logic, without unnecessary ties to specific deployment environments. Applications developed in Spring are more reliable, scalable and very simple to build and maintain. Spring was developed as means to help developers manage the business objects of the application. Due to its vast features and flexibilities, Spring became the most loved framework for developing enterprise-level Java-based applications. In the following section, we will see what are the most commonly asked interview questions and their answers to prepare you for Spring-based interviews.

Interview Questions

Basic Interview Questions

1. What is the use of @Autowired annotation?

@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
    }
}

2. What is the role of @ModelAttribute annotation?

The annotation plays a very important role in binding method parameter 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.

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

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.

4. What are the types of Spring MVC Dependency Injection?

There are two types of DI (Dependency Injection):

  • Construction-Based:
    • This type of DI is accomplished when Spring IoC (Inversion of Control) container invokes parameterised constructor having a dependency on other class.
    • 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:
        ​​​​​​​​​​​​@Component
        ​​​​​​​​​​​​public 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 bean's setter method after a non-parameterised 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.

5. What is the importance of session scope?

Session scopes are used to create bean instances for HTTP session. 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
    ​​​​@SessionScope
    ​​​​public class UserBean {
    ​​​​    //some methods and properties
    ​​​​}
    

6. What is the importance of @Required annotation?

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;
    }
}

7. Differentiate between the @Autowired and the @Inject annotations.

@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.

8. Are singleton beans thread-safe?

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.

9. How can you achieve thread-safety in beans?

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.

10. What is the significance of @Repository annotation?

@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.

Intermediate Interview Questions

1. How is the dispatcher servlet instantiated?

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:

<?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 initialises beans that are defined in the file.

2. How is the root application context in Spring MVC loaded?

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.

3. 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?

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.

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

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.

5. Why do we need BindingResults?

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.

6. What are Spring Interceptors?

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.

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

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.

8. What are the differences between the <context:annotation-config> vs <context:component-scan> tags?

<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. How is the form data validation done in Spring Web MVC Framework?

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.

@Component
public 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" />

10. How to get ServletConfig and ServletContext objects in spring bean?

This can be done by either implementing the spring-aware interfaces or by using the @Autowired annotation.

@Autowired
private ServletContext servletContext;

@Autowired
private ServletConfig servletConfig;

Advanced Interview Questions

1. Differentiate between a Bean Factory and an Application Context.

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 BeanFactory ApplicationContext
Internationalization (i18n) Does not provide support for i18n. Provides support for i18n.
Event Publishing Provides 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.
Implementations XMLBeanFactory 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.
Autowiring For autowiring, beans have to be registered in the AutoWiredBeanPostProcessor API. Here, XML configuration can be done to achieve autowiring.

2. How are i18n and localization supported in Spring MVC?

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">
    ​​​​    <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.
    ​​​​<bean class="org.Springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    ​​​​    <property name="interceptors">
    ​​​​        <list>
    ​​​​            <ref bean="localeChangeInterceptor" />
    ​​​​        </list>
    ​​​​    </property>
    ​​​​</bean>
    

3. What do you understand by MultipartResolver?

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 is it possible to use the Tomcat JNDI DataSource in the Spring applications?

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:

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

5. 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?

The validation is generally performed during HTTP POST requests. During HTTP request, 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 MVC Interview Questions during an interview. Spring is a very powerful framework that allows building enterprise-level web applications using Spring MVC. 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.

References

Multiple choice questions

1. Which of the below statements are correct about Spring?

  • a. Spring allows developers to develop enterprise-level web applications.
  • b. Spring allows developers to code in a modular way.
  • c. Spring ensures that application testing is made simple.
  • d. All of the above
  • Answer: d

2. What does the byName type of autowiring do?

  • a. byName mode means there is no autowiring and explicit reference needs to be added.
  • b. byName mode ensures that the autowiring is done by means of the property name. Spring matches and wires the properties with beans of the same name defined in the configuration file.
  • c. In this mode, Spring first autowires by the constructor and if not found, it tries to autowire by type.
  • d. This mode is similar to byType mode but is restricted to non-parameterised constructors.
  • Answer: b

3. Which among the below classes is used for mapping database row to java object in Spring?

  • a. RowMapper
  • b. ResultSet
  • c. RowSetMapper
  • d. ResultSetMapper
  • Answer: a

4. What class is used for giving a class behaviour of DispatcherServlet?

  • a. Repository
  • b. AbstractAction
  • c. AbstractController
  • d. Controller
  • Answer: c

5. Which among the below is the Handler method annotation in Spring?

  • a. @RequestMapping
  • b. @Controller
  • c. @Service
  • d. @Resolve
  • Answer: a

6. What method arguments are used in handler methods using @RequestMapping?

  • a. @Controller
  • b. @Bean
  • c. @RequestParam
  • d. @Service
  • Answer: c

7. Which among the ViewResolvers resolves the view name to the application's directory?

  • a. InternalResolver
  • b. InternalViewResolver
  • c. InternalRequestResolver
  • d. InternalResourceViewResolver
  • Answer: d

8. Which among the below annotation represents that a field cant be null?

  • a. @NotEmpty
  • b. @NotNull
  • c. @NeverNull
  • d. All of the above
  • Answer: b

9. What annotation receives values in the form of regular expression?

  • a. @Pattern
  • b. @Password
  • c. @Email
  • d. @Valid
  • Answer: a

10. What is used to notify the completion of the session processing?

  • a. BindingResult
  • b. HttpStatus
  • c. SessionStatus
  • d. Session
  • Answer: c