Spring Interview Questions

Spring thumbnail

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.
Core Container -The Core Container consists of the Core, Beans, Context, and Expression Language modules
Data Access/Integration- The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules
Web-The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules.
AOP and Instrumentation-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
Test -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.
It also provides mock objects that you can use to test your code in isolation.

2) What are the benefits of Spring Framework?

Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
Inversion of control (IOC): 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.
Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application objects.
MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.
Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).
Exception Handling: 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 BeanFactory 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.
It is called the heart of spring (Core Container) as it contains the IOC Container.

4) What is IOC in Spring?

IOC 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?

1 : Your code gets decoupled so you can easily exchange implementations of an interface with alternative implementations
2 : It is a strong motivator for coding against interfaces instead of implementations
3 : 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.
The ApplicationContext provides:
Bean factory methods for accessing application components.
The ability to load file resources in a generic fashion.
The ability to publish events to registered listeners.
The ability to resolve messages to support internationalization.
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.
Creating a BeanFactory from xml is as follows
: BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));

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

BeanFactory: It Instantiates beans lazily
It has no support for Message Internationalization.
It has no event handling or event propagation mechanism.
ApplicationContext: Beans are instantiated when ApplicationContext is loaded/up.
It supports Message Internationalization
It provides event-propagation to the beans which are participating in listening to ApplicationContext
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 ApplicationContext as:
ClassPathXmlApplicationContext : 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.
ApplicationContext appContext = new ClassPathXmlApplicationContext(“beans.xml”);
FileSystemXmlApplicationContext : 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 :
ApplicationContext appContext = new FileSystemXmlApplicationContext(“F:/java_program/SpringProject/src/com/mycontext/beans.xml”);
XmlWebApplicationContext : XmlWebApplicationContext is used to represent Spring container for web applications.It loads bean definitions from more than one xml Files.
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 1: The spring container finds the bean’s definition from the XML file and instantiates the bean.
2:Using the dependency injection, spring populates all of the properties as specified in the bean definition.
3:The factory calls setBeanName() passing the bean’s ID if the bean implements BeanNameAware interface
4:The factory calls setBeanFactory(), passing an instance of itself if the bean implements BeanFactoryAware interface
5:If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
6:If an init-method is specified for the bean, it will be called.
7:Finally postProcessAfterInitialization() methods will be called if any BeanPostprocessors associated with it.

12) What are the scopes of spring Bean?

singleton: 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.
prototype: A new instance will be created every time the bean is requested.
request: 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.
session: A new bean will be created for each HTTP session by the container.
global-session: This is used to create global session beans for Portlet based applications.
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
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?

Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
Setter-based dependency injection : 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 lazy-init to inform spring container for not creating that bean at application start up. lazy-init is set true to indicate the container.
The default behavior is false
ex-

17) What are the different modes of autowiring?

Spring provides five different way of autowiring of beans.
no- Default,no auto wiring ,set it manually via 'ref' attribute
byName- Auto wiring by property name.If the name of a bean is same as the name of other bean property,auto wire it.
byType- 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
constructor- byType mode in constructor argument
autodetect- 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.
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.
The DispatcherServlet is declared in the web.xml.
Consider the following DispatcherServlet servlet configuration (in the web.xml file.)
<web-app>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

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.
public interface Controller {
/**
* Process the request and return a ModelAndView object which the DispatcherServlet
* will render.
*/
ModelAndView handleRequest( HttpServletRequest request,HttpServletResponse response) throws Exception;
}

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

contextClass- Class that implements WebApplicationContext, which will be used to instantiate the context used by this servlet.
If this parameter isn't specified, the XmlWebApplicationContext will be used.
contextConfigLocation- String which is passed to the context instance (specified by contextClass) to indicate where context(s) can be found.
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).
namespace- the namespace of the WebApplicationContext. Defaults to [servlet-name]-servlet.

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

1: AbstractCommandController
2: SimpleFormController
3: WizardFormController
4: MultiActionController

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 :
1:BeanNameUrlHandlerMapping
2: SimpleUrlHandlerMapping
3:ControllerClassNameHandlerMapping
4:CommonsPathMapHandlerMapping
5:DefaultAnnotaionHandlerMapping
6: RequestMappingHandlerMapping

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.
example:
<bean class = org.springframework.web.servlet.SimpleUrlHandlerMapping>
<property name ="mappings">
<props>
<prop key ="/saveEmployee.html">saveEmployeeController</prop>
</props>
</property>
</bean>
<bean id ="saveEmployeeController" class ="com.developerstack.employee.SaveEmployeeController"/>

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.
example:
ModelAndView model = new ModelAndView();
model.addAttribute("menus", menuItems);
model.setViewName("dashboard");
Here the model object now consists of view named as dashboard and the menuItems as model object which we populate in UI using the name menus

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 dashboard 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:
- Convert the controller name to lower case
- remove the controller suffix if exists and add / as prefix
example:
<bean class = org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping>
<bean class ="com.developerstack.employee.SaveEmployeeController"/>
</bean>