Frequently asked Spring Interview Questions with best answers for freshers and experienced developers on Spring AOP, JDBC, MVC, Context etc.
Spring is an open source framework which reduces the complexity of enterprise application development. Spring makes Java application simple, improves testability and provide loose coupling between components.
Spring provides loose coupling through Inversion of control (IoC), also known popularly among developers as Dependency Injection (DI). When we use IoC, container given the dependencies passively to an object rather than an object looking for its dependencies from a container. During instantiation, container gives all the dependencies associated with an object without waiting for the object to make a formal request.
4. Explain the advantages of Spring?
- With the help of Spring we can make our application code less dependent on framework.
- It promotes pluggability: With Spring you can think of application objects as named services. Thus you can swap one service for another without affecting the rest of the application.
- Provides good programming practices: Using an IoC container like Spring reduces the complexity of coding to interfaces, rather than classes.
- Spring applications are easy to test: Application objects will generally be POJOs and POJOs are easy to test.
- Reusing existing components: Spring does not introduce its own solution in areas such as ORM, logging, connection pool or other system services. But, spring makes sure that these components are significantly easier to use.
5. What is Aspect Oriented Programming (AOP)?
Spring provides AOP which enables cohesive application development due to the clear demarcation of business logic from other crosscutting concern, such as auditing, logging and transaction management. Due to this clear separation, application objects perform only business logic and not concerned about the system concerns such as logging or transaction support.
6. Explain the difference between concern and crosscutting concern in Spring AOP?
The concern can be defined as a functionality/feature a programmer wants to implement to address a specific business problem. For example, In eCommerce applications a concern can be stock management, shipping management etc.
Crosscutting concern is a concern than span across almost all modules of an application. For example, logging, security etc.
7. What is Aspect?
An aspect can be defined as modularization of a crosscutting concern. For example, a logging module would be called AOP aspect for logging.
8. What is Joinpoint?
The Joinpoint is defined as the point in your application where we inject aspects. Usually when we write a method for executing a business logic, aspects are plugged in at following Joinpoints.
- Before the start of business logic method
- Once business logic method end
- When business logic throws exception
9. What is Advice?
It is the actual action taken up by an aspect at a particular Joinpoint before or after the method execution. It is the actual piece of code that get executed by the Spring AOP framework during the execution of a program.
10. What are the different types of advices?
Spring AOP support following type of advices
- Before advice : Run an advice before a method executes.
- After advice: Run advice after a method executes.
- After returning advice: Run advice on successful execution of a method.
- After throwing advice: Run advice if a method throws an exception.
- Around advice: Run advice before the methods and it can make a decision on whether the original method can be called or not
11. What is Pointcut?
The Pointcut is an expression language of Spring which determines whether an Advice should run at any Joinpoint based on the criteria specified in the Pointcut expression.
12. What is Introduction?
The Spring introduction allows us to add new methods or attributes to any advised object.
The target object is an object which is advised by one or many aspects. It is also known as advised object.
The process of creating a link between aspects and objects to create an advised object is known as Weaving.
- Lightweight Web development with Plain Old Java Objects(POJO).
- Loose coupling through dependency injection.
- Declarative programming through aspects.
- Boilerplate code reduction through aspects and templates.
- Core Container
- Data Access/Integration
- Aspect Oriented Programming(AOP)
17. What does core container consists of?
Core container consists of
- Expression Language modules.
18. What are core and beans module?
The core and beans module are the most fundamental part of the Spring framework. It defines how beans are created, configured and managed.
19. What is the function of BeanFactory in Core and Beans module?
BeanFactory uses the Inversion of Control(IoC), which separates or takes away the application configuration and dependency specification from the application code.
20. What is context module?
The context module is built on the solid base provided by the Core and Beans modules. The context module adds support for internationalization, event propagation, resource loading and container creation.
21. What is the difference between Core and Context module in Spring?
The Core module makes Spring a container, whereas the context module makes Spring a framework.
22. What are the two types of containers in Spring?
- BeanFactory, which provide basic support for dependency injection.
- Application context that build on BeanFactory by providing application framework services.
23. What is the difference between Spring ApplicationContext and BeanFactory?
Even though both ApplicationContext and BeanFactory supports bean instantiation and wiring, ApplicationContext provides additional features such as Automatic BeanPostProcessor & BeanFactoryPostProcessor registration, ApplicationEvent publication etc.
24. What is the responsibility of BeanFactory class?
BeanFactory class function is to create beans and deliver it to the user when asked for.
25. What happens when ambigious beans or ambigious constructors event takes place in autowiring?
UnsatisfiedDependencyException will be thrown.
26. What are the implementing classes of BeanFactory?
27. What is Expression Language module?
The Spring JDBC module provides a JDBC abstraction layer which eliminates tedious & monotonous JDBC coding and database vendor specific error code parsing, thus making it simpler and easier to use.
31. What does ORM module provides to Spring?
The Object Relational Mapping (ORM) module of Spring provides integration layers for popular ORM APIs(JPA, Hibernate, JDO and iBatis) for fast and easy integration. The spring-orm module makes sure that we use all the features of these OR-mapping frameworks in combination with all of the other features Spring offers.
32. What is Spring OXM module?
The OXM module provides Object/XML mapping implementations for JAXB, Castor, XMLBeans, Xstream etc.
33. What does JMS module provides to Spring?
The Java Messaging Service (JMS) module of Spring has features for producing and consuming messages.
34. What are the transaction management supports provided by spring?
The Transaction module provides declarative transaction management (Here, transactions are managed using annotations or XML based configuration) using Spring AOP and API for programmatic transaction management (Here, transactions are managed programmatically) for all classes.
35. What does web module in Spring consists of?
The web module consists of the
- Web-Portlet modules
36. What is Spring's web module?
Spring's web module supports basic web functionalities such as
- Multipart file upload
- IOC container initialization using Servlet listeners & Web application context
37) How does request flow happens in Spring MVC?
Action taken by DispatcherServlet, which acts as the front controller is listed below.
- Step 1 - Request arrive at the Front Controller, i.e DispatcherServlet. Based on the configuration, DispatcherServlet resolves the theme and locale.
- Step 2 - DispatcherServlet looks for the appropriate Controller(Handler) to handle the request. It also looks for the configured pre-processors and post-processors.
- Step 3 - It will then redirect to the appropriate Controller. On receiving the request, the controller executes the request and returns a view name and a model object to the DispatcherServlet. Have a look at the Steps 4,5,6 in the above image.
- Step 7 - DispatcherServlet resolves the view name send by the Controller and redirect it to the view template. The view template will send back the response html to the DispatcherServlet.
- Step 8 - On receiving the response HTML, DispatcherServlet then sends back the response to the browser.
38. What is Web-Servlet module in Spring?
The Web Struts module supports integration of struts into a Spring application. However, this support is deprecated as of Spring 3.0.
- Injecting dependencies via setter methods.
- Injecting dependencies via constructor
42. How ambiguities among constructor arguments can be dealt in injecting dependencies?
It can be dealt in two ways:
- By index
- By type
43. How Spring application is different from Java application?
The difference lies in how these classes are configured and introduced to each other. Typically a Spring application has an XML file that tells how to configure the classes, known as Spring configuration file.
44. How can we inject prototype bean into singleton in Spring?
It can be done in two ways. They are
- Method injection using lookup-method property
- AOP scoped proxy
45. What is method injection using lookup-method?
Suppose we want to inject prototype bean into singleton bean then we have to use method injection like this:
<bean id="prototype" class="com.a4academics.Prototype" scope="prototype" />
<bean id="singleton" class="com.a4academics.Singleton">
<lookup-method name="createPrototype" bean="prototype" />
Here Singleton class has reference to Prototype class and createPrototype() is a method.
46. What is loose coupling and tight coupling code?
Loose coupling is one of the critical elements in object oriented software development. It allows you to change the implementations of two related objects without affecting the other object. Strong coupling directly affects scalability of an application. Tightly coupled code is difficult to test, reuse and understand.
47. How we can reduce coupling?
One way to reduce coupling is to hide implementation details behind interfaces, so that actual implementation class can be swapped out without impacting the client class.
48. What is the core of Spring's DI container?
49. What are the different Inversion Of Control (IOC) approaches?
- Type1: Interface injection
- Type2: Setter injection
- Type3: Constructor injection
50. What is the scope of Spring bean by default?
51. What is singleton bean?
Singleton beans are created only once by the container and all calls to BeanFactory.getBean() return the same instance.
52. What is prototype bean?
Prototype bean lets the container return a new instance, each time a bean is asked for.
53. What are the additional bean scopes apart from singleton and prototype?
The lifecycle of prototype bean is different than a singleton. When the container is asked to supply a prototype bean, it returns new instance, but the container does not hold on to it past that point. But for singleton container manages the life cycle.
Scopes a bean for a particular HTTP request. Only valid when used in a web capable Spring context(such as with Spring MVC).
57. What is sessions scope?
It is the scope of a bean for an HTTP session. It works only when used in a web capable Spring context(such as with Spring MVC).
58. What is global-session scope?
Scopes a bean for a global HTTP session. Only valid when used in a web capable Spring context(such as with Spring MVC).
59. What is wiring?
The wiring can be defined as a technique via which Spring creates an association between different components of an application.
60. What is autowiring?
Autowiring allows Spring to wire all bean properties automatically by setting the autowire property on each bean that you want autowired.
<bean id=”foo' class='com.a4academics.Foo” autowire=”autowire type”/>
61. What are the types of autowiring?
Four types of autowiring:
62. What is autowiring byName?
It is a technique by which a bean can be identified in the container whose name or id matches the property being wired.
63. What is autowiring byType?
It is a technique by which it matches all properties of the autowired bean with beans whose types are compatible.
64. What is autowiring by constructor?
It is a technique by which it matches a constructor of the autowired bean with beans whose types are compatible to the constructor arguments.
65. What is autowiring by autodetect?
If we assign autowire attribute to autodetect, then container decides the mode of autowiring to use.
66. What is configuration metadata in Spring IOC container?
Using configuration metadata we tell the Spring container as to how to instantiate, configure and assemble the objects in your application.This configuration metadata can be supplied in a simple XML format, annotation or Java code.
67.What is Resource interface?
An application needs to access a variety of resources in different forms, e.g. configuration data stored in a file in the file system, some image data stored in a jar file on the classpath. Spring provides a Resource interface to provide a unified mechanism for accessing resources in a protocol independent manner.
68. What are the implementation classes of Resource interface?
69. What is initialization and destruction in Spring container?
When a bean is created, we need to perform some initialization on the bean that can be done with initialization method. When the bean is removed from the container, some cleanup may be required on the bean which can be done with destruction method. Spring can use two life-cycle methods of each bean to perform this setup and teardown.
<bean id=”foo” class=”com.Spring.Foo” init-method=”setup” destroy-method=”teardown”/>
70. What is defaulting init-method and destroy-method?
When many beans in a configuration file has initialization or destroy methods with same name, you can declare default-init-method and default-destroy-method attributes on the <beans> element in the configuration file instead of declaring multiple init-method and destroy-method for all the beans.
71. What is InitializingBean interface?
It provides afterPropertiesSet() method which is called when the bean is initialized by the container.
72. What is DisposableBean interface?
It provides destroy() method which is called when the bean is disposed by the container.
73. What is the advantage of InitializingBean and DisposableBean interface?
The advantage is that Spring container is able to automatically detect beans without any external configuration.
74. What is the drawback of InitializingBean and DisposableBean interface?
The drawback is that the application beans are coupled with Spring API.
75. What is customizing beans with BeanPostProcessor?
BeanPostProcessor interface defines methods via which we can customize beans to provide our own custom logic for bean instantiation, dependency resolution etc.
76. What are the two interfaces provided by Spring for bean post processing?
These are BeanPostProcessor and BeanFactoryPostProcessor interface.