Top 37 Spring Interview Questions And Answers For Experienced Pdf

1. Name some of the design patterns used in Spring Framework ?


Spring Framework is using a lot of design patterns, some of the common ones are:

Singleton Pattern: Creating beans with default scope.
Factory Pattern: Bean Factory classes
Prototype Pattern: Bean scopes
Adapter Pattern: Spring Web and Spring MVC
Proxy Pattern: Spring Aspect Oriented Programming support
Template Method Pattern: JdbcTemplate, HibernateTemplate etc
Front Controller: Spring MVC DispatcherServlet
Data Access Object: Spring DAO support
Dependency Injection and Aspect Oriented Programming

Top 37 Spring Interview Questions And Answers For Experienced Pdf

2. What is Spring DAO ?


Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in a consistent and easy way. For example we have JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport and JpaDaoSupport for respective technologies.

Spring DAO also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.

3. How to integrate Spring and Hibernate Frameworks ?


We can use Spring ORM module to integrate Spring and Hibernate frameworks, if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.

Also Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for hibernate boiler-plate code for transaction management.

4. Differentiate between constructor injection and setter injection ?

Constructor Injection vs Setter Injection
Constructor Injection Setter Injection
There is no partial injection. There can be partial injection.
It doesn’t override the setter property. It overrides the constructor property.
It will create a new instance if any modification is done. It will not create new instance if any modification is done.
It works better for many properties. It works better for few properties.

5. What are some of the best practices for Spring Framework ?


Some of the best practices for Spring Framework are:

Avoid version numbers in schema reference, to make sure we have the latest configs.
Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
For application level properties, best approach is to create a property file and read it in the spring bean configuration file.
For smaller applications, annotations are useful but for larger applications annotations can become a pain. If we have all the configuration in xml files, maintaining it will be easier.
Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that gets usually added when you create projects through Spring Tool Suite templates.
If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
Use dependency injection when there is actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.

6. How many modules are there in Spring Framework and what are they ?


There are around 20 modules which are generalized into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test.Spring Framework Architecture – Spring Interview
Spring Core Container – This layer is basically the core of Spring Framework. It contains the following modules :
Spring Core
Spring Bean
SpEL (Spring Expression Language)
Spring Context
Data Access/Integration – This layer provides support to interact with the database. It contains the following modules :
JDBC (Java DataBase Connectivity)
ORM (Object Relational Mapping)
OXM (Object XML Mappers)
JMS (Java Messaging Service)
Web – This layer provides support to create web application. It contains the following modules :
Web – MVC
Web – Socket
Web – Portlet
Aspect Oriented Programming (AOP) – In this layer you can use Advices, Pointcuts etc., to decouple the code.
Instrumentation – This layer provides support to class instrumentation and classloader implementations.
Test – This layer provides support to testing with JUnit and TestNG.
Few Miscellaneous modules are given below:

Messaging – This module provides support for STOMP. It also supports an annotation programming model that is used for routing and processing STOMP messages from WebSocket clients.
Aspects – This module provides support to integration with AspectJ.

7. What are the benefits of using Spring ?


Spring targets to make Java EE development easier. Here are the advantages of using it:

Lightweight: there is a slight overhead of using the framework in development
Inversion of Control (IoC): Spring container takes care of wiring dependencies of various objects, instead of creating or looking for dependent objects
Aspect Oriented Programming (AOP): Spring supports AOP to separate business logic from system services
IoC container: it manages Spring Bean life cycle and project specific configurations
MVC framework: that is used to create web applications or RESTful web services, capable of returning XML/JSON responses
Transaction management: reduces the amount of boiler-plate code in JDBC operations, file uploading, etc., either by using Java annotations or by Spring Bean XML configuration file
Exception Handling: Spring provides a convenient API for translating technology-specific exceptions into unchecked exceptions.

8. What Spring sub-projects do you know ?


Describe them briefly.
Core – a key module that provides fundamental parts of the framework, like IoC or DI
JDBC – this module enables a JDBC-abstraction layer that removes the need to do JDBC coding for specific vendor databases
ORM integration – provides integration layers for popular object-relational mapping APIs, such as JPA, JDO, and Hibernate
Web – a web-oriented integration module, providing multipart file upload, Servlet listeners, and web-oriented application context functionalities
MVC framework – a web module implementing the Model View Controller design pattern
AOP module – aspect-oriented programming implementation allowing the definition of clean method-interceptors and pointcuts.

Top 37 Spring Interview Questions And Answers For Experienced Pdf

9. What is @Qualifier annotation in Spring ?


You can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.

10. What is @Required annotation in Spring ?


This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.
Suppose you have very large application and you get NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.

11. What are 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.

12. What do you understand by Aspect Oriented Programming ?


Enterprise applications have some common cross-cutting concerns that is applicable for different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.

AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible in normal object oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data. Read more about Spring AOP support at Spring AOP Example.

13. What is the difference between Bean Factory and Application Context ?


BeanFactory is an interface representing a container that provides and manages bean instances. The default implementation instantiates beans lazily when getBean() is called.

ApplicationContext is an interface representing a container holding all information, metadata, and beans in the application. It also extends the BeanFactory interface but the default implementation instantiates beans eagerly when the application starts. This behavior can be overridden for individual beans.

For all differences, please refer to the reference.

14. How to define the scope of a bean ?


To set Spring Bean’s scope, we can use @Scope annotation or “scope” attribute in XML configuration files. There are five supported scopes:

For differences, please refer here.

15. How does the scope Prototype work ?

Scope prototype means that every time you call for an instance of the Bean, Spring will create a new instance and return it. This differs from the default singleton scope, where a single object instance is instantiated once per Spring IoC container.

16. What is dependency injection(IOC) in Spring ?


The basic concept of the dependency injection (also known as Inversion of Control pattern) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

Top 37 Spring Interview Questions And Answers For Experienced Pdf

17. What are ways to inject dependency in Spring ?


There are two ways to do dependency injection in Spring.
Dependency injection via setter method
Dependency injection via constructor.

18. What is spring annotation based configuration ?

You can do dependency injection via annotation also instead of XML configuration. You can define bean autowiring using annotations. You can use @Component,@Repository,@Service and @Controller annotation to configure bean in Spring application.

Annotations wiring is not turned on by default. You need to turn it on using :

Once you put above code, you can start using annotation on class , fields or methods.

19. What are different bean scopes in Spring ?


There are 5 types of bean scopes supported in spring

singleton – Scopes a single bean definition to a single object instance per Spring IoC container.
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP session.

20. What do you mean by bean autowiring in Spring ?


In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in .The Spring container can autowire relationships between collaborating beans without using and elements which helps cut down on the amount of XML configuration

21. Describe DispatcherServlet ?


The DispatcherServlet is the core of Spring Web MVC framework. It handles all the HTTP requests and responses. The DispatcherServlet receives the entry of handler mapping from the configuration file and forwards the request to the controller. The controller then returns an object of Model And View. The DispatcherServlet checks the entry of view resolver in the configuration file and calls the specified view component.

22. What is a Controller in Spring MVC ?


Simply put, all the requests processed by the DispatcherServlet are directed to classes annotated with @Controller. Each controller class maps one or more requests to methods that process and execute the requests with provided inputs.

If you need to take a step back, we recommend having a look at the concept of the Front Controller in the typical Spring MVC architecture.

23. How does the @RequestMapping annotation work ?


The @RequestMapping annotation is used to map web requests to Spring Controller methods. In addition to simple use cases, we can use it for mapping of HTTP headers, binding parts of the URI with @PathVariable, and working with URI parameters and the @RequestParam annotation.

24. What is Application Context and what are its functions ?


ApplicationContext is an central interface for providing configuration information to an application.
An ApplicationContext provides the following functionalities:

Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons.
The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
The ability to publish events. Implementations must provide a means of registering event listeners.
Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

Top 37 Spring Interview Questions And Answers For Experienced Pdf

25. How to handle exceptions in Spring MVC environment ?


There are three ways to handle exceptions in Spring MVC:

Using @ExceptionHandler at controller level – this approach has a major feature – the @ExceptionHandler annotated method is only active for that particular controller, not globally for the entire application
Using HandlerExceptionResolver – this will resolve any exception thrown by the application
Using @ControllerAdvice – Spring 3.2 brings support for a global @ExceptionHandler with the @ControllerAdvice annotation, which enables a mechanism that breaks away from the older MVC model and makes use of ResponseEntity along with the type safety and flexibility of @ExceptionHandler.

26. What is Spring MVC Interceptor and how to use it ?


Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion.

We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.

We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too.

27. What is Spring Framework ?


Spring is one of the most widely used Java EE framework. Spring framework core concepts are “Dependency Injection” and “Aspect Oriented Programming”.

Spring framework can be used in normal java applications also to achieve loose coupling between different components by implementing dependency injection and we can perform cross cutting tasks such as logging and authentication using spring support for aspect oriented programming.

Report Ad
I like spring because it provides a lot of features and different modules for specific tasks such as Spring MVC and Spring JDBC. Since it’s an open source framework with a lot of online resources and active community members, working with Spring framework is easy and fun at same time.
What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments.

28. What do you understand by @Autowired annotation ?


The @Autowired annotation provides more accurate control over where and how autowiring should be done. This annotation is used to autowire bean on the setter methods, constructor, a property or methods with arbitrary names or multiple arguments. By default, it is a type driven injection.

For Example:

public class Employee

private String name;
public void setName(String name)
{; }
public string getName()
{ return name; }

29. What do you understand by @Qualifier annotation ?


When you create more than one bean of the same type and want to wire only one of them with a property you can use the @Qualifier annotation along with @Autowired to remove the ambiguity by specifying which exact bean should be wired.

For example, here we have two classes, Employee and EmpAccount respectively. In EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.

public class Employee
private String name;
public void setName(String name)
{; }
public string getName()
{ return name; }

30. What do you understand by @RequestMapping annotation ?


@RequestMapping annotation is used for mapping a particular HTTP request method to a specific class/ method in controller that will be handling the respective request. This annotation can be applied at both levels:

Class level : Maps the URL of the request
Method level: Maps the URL as well as HTTP request method .

Top 37 Spring Interview Questions And Answers For Experienced Pdf

31. What is the difference between Spring AOP and AspectJ AOP ?


AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:

Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
One of the shortcoming of Spring AOP is that it can be applied only to the beans created through Spring Context.

32. What do you understand by Dependency Injection ?


Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.

Some of the benefits of using Dependency Injection are: Separation of Concerns, Boilerplate Code reduction, Configurable components and easy unit testing.

33. Which is the best way of injecting beans and why ?


The recommended approach is to use constructor arguments for mandatory dependencies and setters for optional ones. Constructor injection allows injecting values to immutable fields and makes testing easier.

34. Are singleton beans thread-safe ?


No, singleton beans are not thread-safe, as thread safety is about execution, whereas the singleton is a design pattern focusing on creation. Thread safety depends only on the bean implementation itself.

35. What does the Spring bean lifecycle look like ?


First, a Spring bean needs to be instantiated, based on Java or XML bean definition. It may also be required to perform some initialization to get it into a usable state. After that, when the bean is no longer required, it will be removed from the IoC container.

36. What is the Spring Java-Based Configuration ?


It’s one of the ways of configuring Spring-based applications in a type-safe manner. It’s an alternative to the XML-based configuration.

Also, if you want to migrate your project from XML to Java config, please refer to this article.

37. What are Dispatcher Servlet and Context Loader Listener ?


Simply put, in the Front Controller design pattern, a single controller is responsible for directing incoming HttpRequests to all of an application’s other controllers and handlers.

Spring’s DispatcherServlet implements this pattern and is, therefore, responsible for correctly coordinating the HttpRequests to the right handlers.

On the other hand, ContextLoaderListener starts up and shuts down Spring’s root WebApplicationContext. It ties the lifecycle of ApplicationContext to the lifecycle of the ServletContext. We can use it to define shared beans working across different Spring contexts.