Spring Interview Questions And Answers For Experienced Pdf

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

2. What is Spring DAO?
Answer: 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 JpaDao Support for SVR 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?
Answer: 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 hibernating 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 a new instance if any modification is done.
It works better for many properties. It works better for a few properties.

5. What are some of the best practices for Spring Framework?
Answer: 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 the listener.
Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
For application-level properties, the 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 using Service and for DAO beans use @Repository.
Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that get 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 an 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 a web application. It contains the following modules :
Web – MVC
Web – Socket
Web – Portlet
Aspect-Oriented Programming (AOP) – In this layer you can use Advice, 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 the 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. (E Learning Portal)

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.

9. What is @Qualifier annotation in Spring?
Answer: You can have more than one bean of the 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?
Answer: 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 a very large application and you get NullPointerExceptions because the 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 the benefits of the Spring Framework?
Answer: Lightweight: Spring is lightweight when it comes to size and transparency.

The basic version of the 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?
Answer: Enterprise applications have some common cross-cutting concerns that are applicable to 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?
Answer: 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?
Answer: To set Spring Bean’s scope, we can use @Scope annotation or “scope” attribute in XML configuration files.

There are five supported scopes:

  • singleton
  • prototype
  • request
  • session
  • global-session
  • For differences, please refer here.

15. How does the scope Prototype work?
Answer: 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?
Answer: 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.

17. What are ways to inject dependency in Spring?
Answer: There are two ways to do dependency injection in Spring.
Dependency injection via setter method
Dependency injection via the constructor.

18. What is spring annotation-based configuration?
Answer: 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 the Spring application.

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

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

19. What are different bean scopes in Spring?
Answer: 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?
Answer: In the Spring framework, you can wire beans automatically with the 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?
Answer: The DispatcherServlet is the core of the 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?
Answer: 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?
Answer: 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 the Application Context and what are its functions?
Answer: ApplicationContext is a 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.

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?
Answer: 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 – handle, post handle and afterCompletion.

We can create spring interceptor by implementing a 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 the Spring Framework?
Answer: Spring is one of the most widely used Java EE frameworks. 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 the same time.

28. What do you understand by @Autowired annotation?
Answer: 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 of driven injection.

For Example:

public class Employee

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

29. What do you understand by @Qualifier annotation?
Answer: 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 it’s specified that bean with id emp1 must be wired.


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

30. What do you understand by RequestMapping annotation ?
Answer: RequestMapping annotation is used for mapping a particular HTTP request method to a specific class/ method in the 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.

31. What is the difference between Spring AOP and AspectJ AOP?
Answer: 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 shortcomings 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?
Answer: 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 ?
Answer: 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. (Spring Hibernate Training Online

34. Are singleton beans thread-safe?
Answer: 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?
Answer: 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?
Answer: 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?
Answer: Simply put, in the Front Controller design pattern, a single controller is responsible for directing incoming HTTP requests to all of an application’s other controllers and handlers.

Spring’s DispatcherServlet implements this pattern and is, therefore, responsible for correctly coordinating the HTTP requests 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.

Note: Browse latest  hibernate interview questions and Hibernate tutorial. Here you can check  Hibernate Training details and Hibernate training videos for self learning. Contact +91 988 502 2027 for more information.


Coupon Code - GET30
* Terms & Conditions Apply