Spring Interview Questions and Answers

1) What is Spring Framework? What are it’s main modules?

The Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure part so you can focus on your application part.Currently it consists of five major modules divided again different submodules These are follows.<br> <strong>Core Container</strong> -The Core Container consists of the Core, Beans, Context, and Expression Language modules<br> <strong>Data Access/Integration</strong>- The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules<br> <strong>Web</strong>-The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules.<br> <strong>AOP and Instrumentation</strong>-Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated<br> <strong>Test</strong> -The Test module supports the testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts.<br> It also provides mock objects that you can use to test your code in isolation.

2) What are the benefits of Spring Framework?

<strong>Lightweight</strong>: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.<br> <strong>Inversion of control (IOC)</strong>: Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.<br> <strong>Aspect oriented (AOP)</strong>: Spring supports Aspect oriented programming and separates application business logic from system services.<br> Container: Spring contains and manages the life cycle and configuration of application objects.<br> <strong>MVC Framework</strong>: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.<br> <strong>Transaction Management</strong>: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).<br> <strong>Exception Handling</strong>: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.

3) What is a core container in Spring?

A <strong>BeanFactory</strong> is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.<br> It is called the heart of spring (<strong>Core Container</strong>) as it contains the IOC Container.

4) What is IOC in Spring?

<strong>IOC</strong> is a design pattern followed to achieve loose coupling between application components.Spring uses this pattern to achieve it. It is named as Inversion of control as we are taking backing the control from dependent components and throwing it to some container.

5) What is the benefits of following IOC pattern?

<strong>1 :</strong> Your code gets decoupled so you can easily exchange implementations of an interface with alternative implementations<br> <strong>2 :</strong> It is a strong motivator for coding against interfaces instead of implementations<br> <strong>3 :</strong> It's very easy to write unit tests for your code because it depends on nothing else than the objects it accepts in its constructor/setters and you can easily initialize them with the right objects in isolation.

6) What is ApplicationContext in Spring?

The ApplicationContext is the central interface within a Spring application for providing configuration information to the application.<br> The <strong>ApplicationContext</strong> provides:<br> Bean factory methods for accessing application components.<br> The ability to load file resources in a generic fashion.<br> The ability to publish events to registered listeners.<br> The ability to resolve messages to support internationalization.<br> provides Inheritance support from a parent context.

7) What is the significance of BeanFactory interface in Spring?

BeanFactory helps in creating Spring object with some basic functionality around object management through a well defined configuration framework.<br> Creating a BeanFactory from xml is as follows<br>: <strong>BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml")); </strong>

8) What is the difference between Beanfactory and ApplicationContext in Spring?

<strong>BeanFactory</strong>: It Instantiates beans lazily<br/> It has no support for Message Internationalization.<br/> It has no event handling or event propagation mechanism.<br/> <strong>ApplicationContext</strong>: Beans are instantiated when ApplicationContext is loaded/up.<br/> It supports Message Internationalization<br> It provides event-propagation to the beans which are participating in listening to ApplicationContext <br> i.e. the beans implementing ApplicationListener interface.

9) What are the common implementations of the Application Context ?

There are three most commonly used implementation of <strong>ApplicationContext</strong> as:<br> <strong>ClassPathXmlApplicationContext</strong> : It loads the context definition from an XML file present in the classpath, treating context definitions as classpath resources. File ‘beans.xml’ should be present in classpath of application.<br> ApplicationContext appContext = new ClassPathXmlApplicationContext(“beans.xml”);<br> <strong>FileSystemXmlApplicationContext</strong> : It loads the context definition from an XML file present in the filesystem. Need to give absolute path of the file ‘beans.xml’ as given below :<br> ApplicationContext appContext = new FileSystemXmlApplicationContext(“F:/java_program/SpringProject/src/com/mycontext/beans.xml”);<br> <strong>XmlWebApplicationContext</strong> : XmlWebApplicationContext is used to represent Spring container for web applications.It loads bean definitions from more than one xml Files. <br> we can specify their locations in contextConfigLocation parameter of ContextLoaderListener in web.xml file.

10) What is a spring Bean?

Any normal java class that is initialized by Spring IOC container is called Spring Bean. Spring uses ApplicationContext to get the Spring Bean instance.

11) What is lifecycle of a bean in Spring?

Spring container performs the following to get a qualified bean.Those steps form the lifecycle of a bean <strong>1:</strong> The spring container finds the bean’s definition from the XML file and instantiates the bean.<br> <strong>2:</strong>Using the dependency injection, spring populates all of the properties as specified in the bean definition.<br> <strong>3:</strong>The factory calls setBeanName() passing the bean’s ID if the bean implements BeanNameAware interface<br> <strong>4:</strong>The factory calls setBeanFactory(), passing an instance of itself if the bean implements BeanFactoryAware interface<br> <strong>5:</strong>If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.<br> <strong>6:</strong>If an init-method is specified for the bean, it will be called.<br> <strong>7:</strong>Finally postProcessAfterInitialization() methods will be called if any BeanPostprocessors associated with it.

12) What are the scopes of spring Bean?

<strong>singleton</strong>: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.<br> <strong>prototype</strong>: A new instance will be created every time the bean is requested.<br> <strong>request</strong>: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.<br> <strong>session</strong>: A new bean will be created for each HTTP session by the container.<br> <strong>global-session</strong>: This is used to create global session beans for Portlet based applications.<br> Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes provided by the framework.

13) What is Dependency Injection in Spring?

Dependency Injection, an aspect of Inversion of Control (IoC).This concept reveals that you don't create your objects ,just configure it the way to be created<br> The container will be all responsible for creating your desired object and hooking it to the dependent modules or components.

14) What are the different types of DI used in spring?

<strong>Constructor-based dependency injection</strong>: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.<br> <strong>Setter-based dependency injection</strong> : Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

15) What is Bean Wiring in Spring?

Bean wiring is the process of hooking a bean to the container i.e to configure the metadata of our beans to be picked up by our container.

16) What is lazy instantiation of beans in Spring?

Some applications require beans to instnatiate only when they are required.spring provides an attribute called <strong>lazy-init</strong> to inform spring container for not creating that bean at application start up. lazy-init is set true to indicate the container.<br/> The default behavior is false</br> ex- <bean id = "testBean" class = "com.developerstack.spring.TestBean" lazy-init = "true"/>

17) What are the different modes of autowiring?

Spring provides five different way of autowiring of beans.<br/> <strong>no</strong>- Default,no auto wiring ,set it manually via 'ref' attribute<br/> <strong>byName</strong>- Auto wiring by property name.If the name of a bean is same as the name of other bean property,auto wire it.<br/> <strong>byType</strong>- Auto wiring by property data type.If data type of a bean is compatible with the data type of other bean property then auto wire it<br/> <strong>constructor</strong>- byType mode in constructor argument<br/> <strong>autodetect</strong>- If a default constructor is found ,use "autowire by constructor" otherwise use "auto wire byType"

18) What is the use of @Qualifier annotation in spring?

If we are using autowiring of 'byType' mode spring fails to instantiate when it finds two or more beans of same class type. In this case we use @qualifier to differentiate between same type of beans .

19) What is DispatcherServlet and its functionalities?

DispatcherServlet a central servlet that dispatches requests to controllers and offers other functionality facilitating the development of web applications.<br/> DispatcherServlet completely integrated with the Spring IoC container and allows you to use every other feature that Spring has.It is so called the front controller.<br/> The DispatcherServlet is declared in the web.xml.<br/> Consider the following DispatcherServlet servlet configuration (in the web.xml file.)<br/> <strong> &lt;web-app&gt; <br/> &lt;servlet&gt;<br/> &lt;servlet-name&gt;test&lt;/servlet-name&gt;<br/> &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;<br/> &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;<br/> &lt;/servlet&gt;<br/> &lt;servlet-mapping&gt;<br/> &lt;servlet-name&gt;test&lt;/servlet-name&gt;<br/> &lt;url-pattern&gt;*.do&lt;/url-pattern&gt;<br/> &lt;/servlet-mapping&gt;<br/> &lt;/web-app&gt; </strong>

20) What is a controller in spring?

A controller in spring is an interface which defines a single method that is responsible for handling a request and returning an appropriate model and view.<br/> public interface Controller {<br/> /**<br/> * Process the request and return a ModelAndView object which the DispatcherServlet<br/> * will render.<br/> */<br/> ModelAndView handleRequest( HttpServletRequest request,HttpServletResponse response) throws Exception;<br/> }

21) What are the different type of initilization parameters for DispatcherServlet?

<strong>contextClass</strong>- Class that implements WebApplicationContext, which will be used to instantiate the context used by this servlet.<br/> If this parameter isn't specified, the XmlWebApplicationContext will be used.<br/> <strong>contextConfigLocation</strong>- String which is passed to the context instance (specified by contextClass) to indicate where context(s) can be found. <br/> The string is potentially split up into multiple strings (using a comma as a delimiter) to support multiple contexts (in case of multiple context locations, of beans that are defined twice, the latest takes precedence).<br/> <strong>namespace</strong>- the namespace of the WebApplicationContext. Defaults to [servlet-name]-servlet.

22) What are different type of controller implementations in spring?

<strong>1:</strong> AbstractCommandController<br/> <strong>2:</strong> SimpleFormController<br/> <strong>3:</strong> WizardFormController<br/> <strong>4:</strong> MultiActionController<br/>

23) What is a HandlerMapping?

HandlerMapping is responsible for mapping incoming web requests to appropriate handler that can process the request. Dispatcher Servlet delegates the request to HandlerMapping to inspect the request and return appropriate HandlerExecutionChain that can handle the request.

24) What are the different types of handlerMapping implementations available in spring?

The following are the different HandlerMapping implementations :<br/> <strong>1:</strong>BeanNameUrlHandlerMapping<br/> <strong>2:</strong> SimpleUrlHandlerMapping<br/> <strong>3:</strong>ControllerClassNameHandlerMapping<br/> <strong>4:</strong>CommonsPathMapHandlerMapping<br/> <strong>5:</strong>DefaultAnnotaionHandlerMapping<br/> <strong>6:</strong> RequestMappingHandlerMapping<br/>

25) What is SimpleUrlHandlerMapping?

It is one of the implementations of HandlerMappings.It is the most commonly used HandlerMapping. We have to set the mapping property of the SimpleUrlHandlerMapping with key as request and value as the Handler.<br/> example:<br/> &lt;bean class = org.springframework.web.servlet.SimpleUrlHandlerMapping&gt;<br/> &lt;property name ="mappings"&gt;<br/> &lt;props&gt;<br/> &lt;prop key ="/saveEmployee.html"&gt;saveEmployeeController&lt;/prop&gt;<br/> &lt;/props&gt;<br/> &lt;/property&gt;<br/> &lt;/bean&gt;<br/> &lt;bean id ="saveEmployeeController" class ="com.developerstack.employee.SaveEmployeeController"/&gt;<br/>

26) What is ModelAndView?

ModelAndView is an Object which contains both Model and View.The Handler returns the ModelAndView object and DispatcherServlet resolves the view using ViewResolver and View.<br/> example:<br/> ModelAndView model = new ModelAndView();<br/> model.addAttribute("menus", menuItems);<br/> model.setViewName("dashboard");<br/> Here the model object now consists of view named as dashboard and the <strong>menuItems</strong> as model object which we populate in UI using the name <strong>menus</strong>

27) What is ViewResolver?

DispatcherServlet uses the ViewResolver Mapping and dispatches the request to an appropriate view. In the previous questions the logical view name is <strong>dashboard </strong> which resolved by ViewResolver using the configuration provided in web context xml file.

28) What is ControllerClassNameHandlerMapping?

It is the implementation of HandlerMapping where the name of the controller itself acts as the request. The conventions to be followed while using it:<br/> - Convert the controller name to lower case<br/> - remove the controller suffix if exists and add / as prefix<br/> example:<br/> &lt;bean class = org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&gt;<br/> &lt;bean class ="com.developerstack.employee.SaveEmployeeController"/&gt;<br/> &lt;/bean&gt;

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.