Java Spring MVC Interview Questions – MUST Have

By | December 11, 2016

This Web Developer Interview Questions post is about MVC Interview Questions for Java Spring that will explore various features, concepts and FAQs regarding Java Spring Framework. It’s basically a thorough collection of most frequently asked Spring MVC Interview Questions for Java developers. We already have covered another comprehensive list of Interview Questions related to Microsoft ASP.NET MVC that you can follow here.

You can find latest Java Developer Jobs at the end of this Java Spring MVC tutorial.

Java Spring MVC Interview Questions List

What is Java Spring MVC Framework?

Spring MVC is a solution to use the concept of MVC in Spring Framework. In Spring MVC, it is done with the help of DispatcherServlets. Before going some in depth of spring mvc, lets have a quick look on what MVC is.

MVC, is a shorthand of Model View Controller, which separates the different areas of our application and provides loose coupling. While Model have the application data, view is responsible for rendering the model data and display on HTML page. Controller’s responsibility is to process user requests, building the appropriate model and redirect to a particular view to display.

Spring MVC Framework uses dispatcher servlet for handling HTTP Request and provides HTTP Response. Lets have a look using diagram how Dispatcher servlets handles request and provides response and some components that are being used by dispatcher servlet.Java Spring MVC Framework

The above diagram illustrates the events for an HTTP request to DispatcherServlet. Below is the brief description about the events :

  • Once DispatcherServlet receives the HTTP request, first thing it does is to go to HandlerMapping to call the controller corresponding to the request.
  • Once control comes to Controller, it takes the request and call the methods and executes the business logic and sets the data in model. Once it does all these it returns the view name to DispatcherServlet.
  • Taking help from the view resolver, Dispatcher servlet picks the view for the request.
  • Once dispatcher servlet gets the view, it passes the model data to view and the same view has been displayed on browser.

Back to top

What are the benefits of using Spring Framework?

Followings are the key benefits of using Java Spring MVC Framework:

  • Spring uses POJO model that is easy for development.
  • Dependency Injection design pattern is used in spring which provides loose coupling.
  • It uses Light weight IoC containers that are lightweight when compared with EJB containers.
  • Spring provides transaction management, which is very useful.
  • Spring code is more modular and more readable.
  • Spring web framework uses MVC which is an advantage when compared to other Web Frameworks.

Back to top

What are the Modules in Spring Framework? Kindly explain the key modules in Spring in detail including Core, Bean, Context, Expression Language, JDBC, ORM, OXM, JMS etc.

Spring, a potential candidate for all enterprise applications. It provides a number of modules to pick according to need. We will discuss all the modules one by one. But going forward lets take an simple diagram that illustrates all the modules. We will subdivide some modules to a submodule that these corresponds to:Modules in Java Spring

Lets dig into each module one by one:

WEB Module:

Web layer provides support to create web related stuff using portlet, servlet, web-socket. Here Spring MVC comes into picture. Where portlet module provides mvc implementation to be used in portlet, web module provides basic web integration features, web-mvc module contains mvc and rest webservices for web applications.

DataAccess Module:

Data Access layer consists of different modules as ORM, OXM, JMX, JMS, JDBC.

Jdbc module provides a abstract layer that enables user to get rid of Jdbc coding. Transaction modules supports transaction management(Declarative transaction) for the classes that implements the specific interfaces. ORM provides integration layer for ORM api’s including ORM frameworks like Hibernate, JPA. OXM provides a layer that supports Object/XML mapping such as JAXB, XML Beans etc. JMS module implements features for consuming and producing messages.

Core Module:

Core module layer consists of bean, expressionLanguage, core and context. Where Bean module provides BeanFactory which is implementation of factory pattern, core provides features like IoC and dependency injection, context module provides support for  internationalization, resource loading, it also supports EJB, JMX etc. ExpressionLanguage provides support to method invocation, accessing collections and indexers, named variables, logical andarithmeticic operators.

AOP, Instrumentation, Aspects and Messaging:

AOP module provides aspect oriented programming capability that enables user to write clean code using interceptors that decouple the code and functionality that can be seprated, Aspects module provides integration with AspectJ, yet another powerful aspect of aspect oriented programming, Instrumentation module provides class loader implementation to be used in certain application servers, Messaging module provides foundation for messaging based applications.


Testing module provides support for spring application to test with testing frameworks like TestNG and JUnit.

Back to top

What is Dependency Injection? What are the different Types of IoC Dependency Injection? What are the benefits of using DI? How to implement DI in Spring Framework?

Dependency Injection related can be considered to be the most important question in list of Spring MVC Interview Questions. Dependency is something what we can say an object that can be used in other service that needs it, without having much knowledge about it and constructed object will be passed to service by some external entity. Now a service that needs this object either can create an object or what can be done is, a readymade object is passed to the service. Now in earlier version what we are doing is we are creating a hard dependency between object and service that is creating the object. To get rid of this what can be done is, a readymade object is passed to the service and it will be used wherever is required. This is dependency injection, where object is passed to service by external entity and service is not responsible for creating object.

Lets take a simple example:

Lets say we have a service that regularly checks for data modification in database and this service uses a class called ModificaitonPoller that regularly polls the modification of data.

Now lets simulate this using a traditional approach:

In this example what we have created is we have created a dependency between DataModificationService and ModificationPoller.

Lets try to achieve using DI (Dependency Injection) approach:

Here ModificationPoller is implemented/created somewhere else and passed as dependency in DataModificaitonService at the time of object construction. This is a simple example of Dependency Injection.

DependencyInjection uses Inversion Of Control(IoC) to resolve dependencies, wherein a client delegates the responsibility of providing dependencies to external entity. Service/Client doesn’t need to know about how to construct the dependencies, these will be provided by some external entity. This separates the responsibilities of use and construction.

Types of InversionOfControl DependencyInjection :

There are three type of IoC DependencyInjection:

  • Inject using Constructer
  • Inject using setters
  • Inject using Interface

Lets take examples of each:

Inject using Constructor

This is same as that we talked earlier, dependency is passed in constructer.

Inject using setters

In this method dependency is injected using setter method. Below is the example for the same.

Inject using Interface

In this approach there will a interface that will provide a setter method for injecting deprendency. Below is the example for the same.

Benefits of DI :

  • Dependency injection looses coupling between class and its dependency.
  • Using DI, one more important principle that is ‘OpenClosePrinciple’ is satisfied, since the service/client is open for extension and close for modification.
  • A lot of boilerplate code is removed from client/service.
  • Ease is testing, using DI testing becomes easy to test, since dependencies can be easily mocked and inject in test.
  • Code becomes more reusable since dependency can be configured differently for other objects.
  • DI allows service/client to be independent and don’t need to have all knowledge of concrete implementation. It helps service to isolate from the design changes if there are any.

Dependency Injection and Spring:

Spring provides two ways to inject dependencies

  • Inject dependency using constructor
  • Inject dependency using setter
  • Inject dependency using annotations

We already covered the concept, lets take example how it can be achieved in spring.

Inject dependency using constructor

To achieve this <constructor-arg> tag will be used. Config file will declare the bean and set the dependency. Lets see how config will look like:

Here we injected the ModificationPoller into DataModificationService.

Java code will moreover look the same as we discussed earlier in inject using constructor.

Inject dependency using Setter

To achieve this, config file will have to declare the bean and inject using the <property> tag. Lets see how config will look like:

Here we injected the ModificationPoller into DataModificationService using setter approach.

Back to top

What is Spring IoC Container? What are different types of IoC Container? Explain each with the help of an implementation example. What are the key differences between various types of IoC Containers?

Before digging more into it, lets talk about IoC. What IoC is? IoC , Inversion of Control is a principle that is driven by DI (Dependency Injection). Dependency Injection is design principle about object construction, how object will be created and how the dependencies will be defined, there are multiple ways to achive this, like injecting dependencies in object constructor or using setter methods or using annotations. Now here container comes into picture, how these dependencies will be injected. The container injects the dependencies when creating bean.

IoC container is responsible for creating, configuring and assembling bean and its dependencies. Xml’s are defined , from where container gets the information about creating bean and what all dependencies needs to be injected while creating this bean.

There are two types of IoC containers

  • Application Context
  • Bean Factory

Application Context

Defined by org.springframework.context.ApplicationContext interface, ApplicationContext is a advanced spring container. ApplicationContext comes with some very handy features like Generic way to load resources, messagesource access, BeanPostProcessor registration etc.

There are several ApplicationContext implementations, mostly used implementations are listed below:

  • FileSystemXmlApplicationContext
  • ClassPathXmlApplicaitonContext
  • XmlWebApplicationContext

Lets discuss one by one with example in which based on file extension, some processing needs to be done. In the example we will not discuss the processing part but surely will demonstrate how the value is been loaded from xml file and how it is been loaded from application context.

FileSystemXmlApplicationContext: As the name suggests it loads the xml config file from file system.

In the example above a class is created named FileExt and the file extension will be set from config file.

And when we code the main class that will load the config file, main class would look like, lets assume the directory in which my config file “c:\\springmvc\\docs”:

ClassPathXmlApplicaitonContext: As the name suggests, it loads the xml file available in classpath. Lets take an example how code will look like. Scenario will be the same and same config will be used.

XmlWebApplicationContext: It can be used only in web applications, and it loads the config file from web app.

Bean Factory

Defined in org.springframework.beans.factory.BeanFactory interface, BeanFactory provides support for Dependency Injection. Like in factory pattern, in which same type of object/bean created, BeanFactory comes with a feature which can create objects/beans of different types.

Lets stick to the same example what we have discussed in ApplicationContext, lets see how code of BeanFactory look like:

It will load the bean using classpath resource.

Now see how to get the value that we defined in config file.

Running the program will load the config file and gets the extension.

Now onward, the following three MVC Interview Questions for Java Spring are related to Spring Beans.

Back to top

What are Spring Beans? How do we add a bean in Java Spring Application?

Spring bean is a java object when we see from a very high level. These are the core parts of our application which are managed by spring container. A spring bean is an object which is created, assembled and managed by spring container. These are created by the config file and the required data that is needed to create the bean. Config files are managed by spring container and based on these config file container creates the beans. Spring container provides the dependencies and other configurations that will be injected to bean, as well as the scope of objects that will be created.

To create/add a bean in spring, we need to provide the bean metadata to container using config files. Below is the example to create a simple bean, called Student, that has two properties, name and age.

Above is the java code for a simple bean. Lets see how it will goes with config file:

Back to top

How to define a  Bean Scope in Spring Framework?

Spring Framework provides different types of scopes to beans, with which we can control the behavior and object instantiation. Below are the scope that Spring MVC Framework provides to a bean:

  • Singleton : Singleton is the default scope and as the name suggests container will create a single instance per IoC container.
  • Request : Container will instantiate bean for HTTP request. This scope can only be used for the HTTP requests, hence it will be applicable wherever the web-aware application.
  • Prototype: Prototype scope enables any number of bean instances, when and where ever requested.
  • Session : Beans configured with session scope, lives with the HTTP session. Similar to request it will also be applicable to web-aware application.
  • Global_session : Global session scope is much more similar to session scope, only difference with this is Portlet web applications.

Lets take an example of how to define scope with a bean.

We can define scope of bean by two ways.

  • In the bean definition tag itself, For Example:
  • Using @Scope annotation for annotation based configuration.

Back to top

What are Inner Beans in Java Spring Framework?

Inner beans concept is much more similar like inner classes concept in java. Wherein a class can be defined under a class. Similarly a bean can also be defined under a bean. The inner bean is supported in both setter <property> and constructor <constructor-arg> injectors.

Lets take an example how inner beans can be created. We have defined a simple class Student and Address bean will be injected in this class by setter injection. Lets see how it will look like:

The config file will have the Address bean injected in the Student bean, lets see how :

Back to top

More Advanced MVC Interview Questions on Java Spring Framework

Explain in detail about Bean life cycle in Spring framework with the help of a diagram?

Spring framework provides several ways to control life cycle of a bean:

  1. Using callback interfaces (InitializingBean and DisposableBean)
  2. Using Aware interfaces
  3. Using init()/destroy() method in config file
  4. Using annotations (@PostConstruct and @PreDestroy)

Before digging into all of these, lets look at the life cycle methods with a diagram, below is the flow with with bean life cycle goes:

Bean Life Cycle in Spring

Using callback interfaces (InitializingBean and DisposableBean)

To initializate bean InitalizingBean interface needs to be implemented which is defined under org.springframework.beans.factory package. It declares a single method afterPropertiesSet(). Bean that implementing this interface required to provide implementation of afterPropertiesSet() and any initlization related code should be added in it.

To destroy bean DisposableBean interface needs to be implemented which is defiled under org.springframework.beans.factory package. It declares a single method destroy(). Bean that implementing this interface required to provide implementation of destroy() method, which will be executed when bean is destroyed.

Method signature for both looks like:

However this approach is not recommended to use, since bean class gets tightly coupled by spring container.

Code example would look like:

Using Aware interfaces

There might be a case when a bean require certain infrastructure dependency. To achive this spring provides a number of aware interfaces. Each interface provides method to inject dependency in the bean, that we need to implement.

Let’s take example of one of the aware interfaces that is ApplicationContextAware  which provides setApplicationContext() method that can be used to set the application instance to bean:

Using init()/destroy() method in config file

As we discussed above in approach #1 using InitializingBean, DisposableBean interfaces, that is easy to use but has a drawback of having tight coupling. An alternative and to overcome this, spring provides yet another way to use init and destroy method in config file. There are two ways to define these:

  1. Local definition: As the name suggests, Local definition will be applicable to single bean. Below is the example for the same, how it will look in beans.xml.
  2. Global definition: Using global definition, methods will be invoked to all beans defined under the tag. Below is the example for the same, how it will look in beans.xml:

Using annotations (@PostConstruct and @PreDestroy)

Spring 2.5 onwards, we can use annotations to control life cycle of bean, that are @PostConstruct and @PreDestroy.

Method annotated with @PostConstruct method will be invoked after the default constructer of bean has been called and before bean’s instance is returned to requesting object.

Method annotated with @PreDestroy will be called just before the it is destroyed inside bean container.

Hopefully, this Spring MVC Interview Question has explained in detail all about bean life cycle with the help of source code.
Back to top
Java E-Commerce Store

What is Bean Factory? How to use XMLBeanFactory? Explain with the help of a practical example?

Bean Factory

Defined in org.springframework.beans.factory.BeanFactory interface, BeanFactory provides support for Dependency Injection. Like in factory pattern, in which same type of object/bean created, BeanFactory comes with a feature which can create objects/beans of different types. There are several implementations of BeanFactory, XMLBeanFactory is one of them.

Lets see with a practical example how we can use XMLBeanFactory:

Suppose a scenario where in type of database will be passed to DAO layer using the config file and based on type of the database some post processing will be done. Lets see how we can achieve the same using XMLBeanFactory.

First thing we need to create is a class within which the property needs to be set. Lets create a class:

Now lets create the config file named Bean.xml, from which we will set the database type

Lets see all together in action with XMLBeanFactory:

What all we have done here:

  • First we have created a factory object, with help of XmlBeanFactory and used ClassPathResource() to load the config file from the classpath.
  • Once the config file will be loaded, we need to get the bean within which the property is defined. We have achieved this using getBean() method. This method used the bean id to get the generic object. Which is later on casted to original object.
  • Once we got the object we used the getter method to get the property what we need.

Back to top

What are the differences between Singleton and Prototype Bean? Give an example of using both?

If we look at both Singleton and Prototype Bean, both comes under the scope of bean. The most basic difference between both is, Singleton, as name suggests there will be only once instance of bean per IoC container, where as in case of prototype bean one can create as many number of bean instances as needed.

Lets take both of them one by one using some examples:


When a bean is declared as singleton, container will create only one instance of that bean and all calling beans will get the same instance matching the bean id and that particular instance will be returned by container. So whenever a bean is created with Singleton instance, exactly one instance of the object will be created so all the calling bean definitions will get the same instance. What container does is whenever a bean with singleton scope is created the instance is kept in cache and the same instance is returned to all requests.

The singleton scope is default scope of bean. Lets see how to create this:

What we have done is, we have created a bean databaseType with singleton scope. We can achieve this by any of these.

Lets create a config file and corresponding java file to see, how it looks like:

Java class of bean type looks like:

Now lets create a Main class and try to create some objects and see if they are equal:

Running the above code what we get in output is:

Both objects are equal

And the reason why we got this output is because the scope is singleton and only one instance is created and passed by the container.


Prototype is yet another scope of bean provided by spring framework. Where Singleton provides one and only instance, prototype scope says there will as many number of instances will provided, where and when needed. To create beans with prototype scope, we can use either of both ways that are listed below:

Lets take the same example that we taken for Singleton. I am not writing code for java class of DataBaseType, since it will be same.

Lets create a config file and corresponding java file to see, how it looks like:

Now lets create a Main class and try to create some objects and see if they are equal or not:

Running the example above what we got in result is:

Both objects are different

And this is expected since beans with prototype scope will have the different instance on each and every call.

Back to top

What is AOP (Aspect Oriented Programming)? Explain in detail with the help of an example? Explain more related concepts including Aspect, Advice, JointPoint, PointCut and Advice Argument etc.

AOP, Aspect Oriented Programming, is a programming technique that provides modularity. What AOP does is, it brakes the program logic into different distinct parts what is called as concerns and it is used to achieve modularity using cross cutting concerns.

Lets try to understand the concept with an example.

Suppose there is mail delivery system, which has a service with multiple methods. Each method’s responsibility is to check the content of mail, lets day one method will check if it is spam or not, one will check if the content is not harmful to the system it is being routed to. Each method logs some and send confirmation to the message client if everything goes fine. Now if you see in each method, there is some logging, so you need to write code for logging in each and every method. Lets suppose a solution which enables you to write a centralized code for logging. Also lets suppose if client says I don’t want any confirmation from methods, so we need to remove the code from all the methods. Which increases the maintainability of code.

What AOP provides us is, AOP separates the concerns like logging, confirmation to client. It separates the concerns and enables you to write all these stuff in a config xml file. Sounds great isn’t it. That’s the beauty of AOP.

There are multiple concepts of AOP, these are listed below:

  • Join point : A Join point is point in a class such as execution of a class or exception handling or so. Spring AOP supports only execution of a class as join point.
  • Advice : Advice is something, that is the action been taken on a particular join point. These are actions that will be executed once program reaches a particular join point. They can be executed before, after, after and before both or on some exception scenario.
  • Pointcut : Pointcut are different type of expressions that are matched on a join point, deciding factor for an advice needs to be run or not.
  • Introduction : There may be scenarios where at a particular advice to add some methods, Introduction enables this thing.
  • Target Object : As name suggests target objects are the objects on which the advice is applied. In spring AOP is implemented using Proxy pattern so the target objects are proxy objects only.
  • Aspect : Aspect is a class that has the ability to cut the concerns. In simple words a class which has JoinPoint, Advice.  This class is configured through a xml configuration or annotation based approach.
  • AOP Proxy : AOP proxy is used to create proxy classes with target classes. Spring used JDK dynamic proxy to achive this.
  • Weaving : Weaving as the name suggests, it is used for linking. Liking of other objects with the aspects. This can be done at runtime, complietime and on class loading. Spring performs weaving at compile time.

AOP implementations are provided by SpringAOP, AspectJ, JBoss AOP.

Back to top

How to setup LDAP authentication using Spring Framework? Explain all steps with proper diagram.

LDAP is LightWeightApplicationProtocol that is a protocol for reading and editing directories over IP network. Lets quickly go through some LDAP terminology that we will be using.

  • Ou – Organization Unit
  • Dn – Distinguished name, which is used to find a person in LDAP server
  • Bind – In this LDAP clients send bind request to LDAP server using credentials.
  • Search – In this Distinguished name of user is retrieved using credentials.
  • Root – it is root element of Ldap directory.
  • BaseDn – BaseDn is a branch in LDAP tree, that is used for LDAP search.

LDAP authentication with spring:

Now lets go through the steps how we can achieve LDAP authentication using spring. First of first thing that we need to do is to add the dependencies to project. Spring ldap and spring security are the dependencies that we need to add to achieve LDAP authentication.

After having dependencies in place, we need to configure the Ldap server. Lets see how to do this:

To perform Ldap search service must have the LDAP account, this is the reason we have provided manager-dn and manager-password. From the xml code written above application binds itself to LDAP server.

Authenticate method will return true or false based on the active directory search.

Alternate approach to this is to use ActiveDirectoryLdapAuthenticationProvider. Below is the example of how it will be used to authenticate:

Back to top

Hopefully, this MVC Interview Questions or FAQs (Frequently Asked Questions) will be helpful for developer to grasp Java Spring Framework in more details. Continue with next part in this series on Java Spring MVC Interview Questions and Answers.

Top Web Developer Interview Questions and Answers Series:


Java Application Development Jobs

[php snippet=8]