Top 100 Spring Interview Questions and Answers (Part 2)

This post will help you get through Spring Interview Questions and Answers from the basic to advanced concepts. It’s useful for both fresher and experienced who want to learn or review about Spring Framework. Let’s learn and grow together.

Spring Interview Questions and Answers

(Part 2)

51.In Spring framework, what is Annotation-based container configuration?
From Spring 2.5 version it is possible to provide configuration by using annotation.
To turn this configuration on, we need to mention <context:annotation-config/> in spring XML file.
Now developer can use annotations like @Required, @Autowired, @Qualifier etc. in a class file to specify the configuration for beans.
Spring container can use this information from annotation for creating and wiring the beans.

52.How will you switch on Annotation based wiring in Spring?
To use Annotation based wiring, we need to turn on Annotation based configuration in Spring.
By default, Annotation based configuration is switched off in Spring. To turn it is we can specify <context:annotation-config/> element in Spring config file.
Once it is turned on, we can use @Autowired annotation or @Required annotation in a Java class for wiring in Spring.

53. What is @Autowired annotation?
We can use @Autowired annotation to auto wire a bean on a setter method, constructor or a field. @Autowired auto wiring is done by matching the data type.
Before using @Autowired annotation we have to register AutowiredAnnotationBeanPostProcessor. This can be done by including <context:annotation-config /> in bean configurat ion file.

54.What is @Required annotation?
We use @Required annotation to a property to check whether the property has been set or not.
Spring container throws BeanInitializationException if the @Required annotated property is not set.
When we use @Required annotation, we have to register RequiredAnnotationBeanPostProcessor in Spring config file.

55.What are the two ways to enable RequiredAnnotationBeanPostProcessor in Spring?
RequiredAnnotationBeanPostProcessor can be enabled in two ways in Spring:
Include <context:annotation-config /> Add Spring context and <context:annotation-config /> in bean
configuration file.

Include RequiredAnnotationBeanPostProcessor in bean configuration file

56. What is @Qualifier annotation in Spring?
We use @Qualifier annotation to mark a bean as ready for auto wiring. This annotation is used along with @Autowired annotation to specify the exact bean for auto wiring by Spring container.

57.How Spring framework makes JDBC coding easier for developers?
Spring provides a mature JDBC framework to provide support for JDBC coding. Spring JDBC handled resource management as well as error handling in a generic way. This reduces the work of software developers.
They just have to write queries and related statements to fetch the data or to store the data in database.

58.What is the purpose of JdbcTemplate?
Spring framework provides JdbcTemplate class that contains many convenient methods for regular tasks like- converting data into primitives or objects, executing prepared or callable statements etc.
This class makes it very easy to work with database in our Application and it also provides good support for custom error handling in database access code.

59.What are the benefits of using Spring DAO?
Some of the benefits of using Spring DAO are:

  1. It makes it easier to work on different data access methods likeJDBC, Hibernate etc.
  2. It provides a consistent and common way to deal with different data access methods.
  3. Spring DAO makes it easier to switch between different data persistence frameworks.
  4. No need for catching framework specific exceptions.

60.What are the different ways to use Hibernate in Spring?
Spring provides two ways to use Hibernate:

  1. We can extend HibernateDAOSupport and apply an AOP interceptor node to use Hibernate.
  2. We can also use HibernateTemplate and Callback to access Hibernate. This is based on Inversion of Control.

61.What types of Object Relational Mapping (ORM) are supported by Spring?
Spring supports following Object Relational Mapping (ORM) frameworks:

Spring Interview Questions and Answers, Object Relational Mapping (ORM)

  1. Hibernate
  2. Java Persistence API (JPA)
  3. TopLink
  4. Java Data Objects (JDO)
  5. Apache Object Relational Bridge (ORB)

62.How will you integrate Spring and Hibernate by using HibernateDaoSupport?
We can use following steps for integrating Spring and Hibernate:

  1. Add dependencies for Spring and Hibernate in pom.xml
  2. Implement DAO from HibernateDaoSupport
  3. Use Hibernate functions via getHibernateTemplate() method

63. What are the different types of the Transaction Management supported by Spring framework?
Spring framework provides support for two types of Transaction Management:

  1. Programmatic: In this method, we have to manage Transaction by programming explicitly. It provides flexibility to a developer, but it is not easier to maintain.
  2. Declarative: In this approach, we can separate Transaction Management from the Application Business code. We can use annotations or XML based configuration to manage the transactions in declarative approach.

64.What are the benefits provided by Spring Framework’s Transaction Management?
Main benefits provided by Spring Transaction Management are:

  1. Consistent: By using Spring Transaction management, we can use consistent programming model across different transaction APIs like- JPA, JDBC, JTA, Hibernate, JPA, JDO etc.
  2. Simplicity: Spring TM provides simple API for managing the transaction programmatically.
  3. Declarative: Spring also supports annotation or xml based declarative transaction management.
  4. Integration: Spring Transaction management is easier to integrate with other data access abstractions of Spring.

65.Given a choice between declarative and programmatic Transaction Management, which method will you choose?
In Spring, Declarative Transaction Management is the preferred choice. This method is very less invasive and it has very less impact in Application Business Logic.
Although Declarative method gives less flexibility than Programmatic method, it is simpler to use and easier to maintain in long run.

66. What is Aspect Oriented Programming (AOP)
Aspect Oriented Programming (AOP) is a programming paradigm that promotes programmers to develop code in different modules that can be parallel or in crosscutting concerns. E.g. To develop banking software, one team can work on business logic for Money withdrawal, Money deposit, Money Transfer etc.
The other team can work on Transaction Management for committing the transaction across multiple accounts.
In an Auto company, one team can work on software to integrate with different components of car. The other team can work on how all the components will send signal and current information to a common dashboard.

67. What is an Aspect in Spring?
An Aspect is the core construct of AOP. It encapsulates the behavior that affects multiple classes in a reusable module.
An Aspect can have a group of APIs that provide cross-cutting features. E.g. A logging module can be an Aspect in an Application.
An application can have multiple of Aspects based on the different requirements.
An Aspect can be implemented by using annotation @Aspect on a class.

68.In Spring AOP, what is the main difference between a Concern and a Cross cutting concern?
A Concern in Spring is the behavior or expectation from an application. It can be the main feature that we want to implement in the application.
A Cross cutting concern is also a type of Concern. It is the feature or functionality that is spread throughout the application in a thin way. E.g. Security, Logging, Transaction Management etc. are cross cutting concerns in an application.

69.What is a Joinpoint in Spring AOP?
In Spring AOP, Joinpoint refers to a candidate point in application where we can plug in an Aspect.
Joinpoint can be a method or an exception or a field getting modified.
This is the place where the code of an Aspect is inserted to add new behavior in the existing execution flow.

70.What is an Advice in Spring AOP?
An Advice in Spring AOP, is an object containing the actual action that an Aspect introduces.
An Advice is the code of cross cutting concern that gets executed.
There are multiple types of Advice in Spring AOP.

71.What are the different types of Advice in Spring AOP?
Spring AOP provides five kinds of Advice:

  1. Before Advice: This type of advice runs just before a method executes. We can use @Before annotation for this.
  2. After (finally) Advice: This type of advice runs just after a method executes. Even if the method fails, this advice will run. We can use @After annotation here.
  3. After Returning Advice: This type of advice runs after a method executes successfully. @AfterReturning annotation can be used here.
  4. After Throwing Advice: This type of advice runs after a method executes and throws an exception. The annotation to be used is @AfterThrowing.
  5. Around Advice: This type of advice runs before and after the method is invoked. We use @Around annotation for this.

72. What is a Pointcut in Spring AOP?
A Pointcut in Spring AOP refers to the group of one or more Joinpoints where an advice can be applied.
We can apply Advice to any Joinpoint. But we want to limit the places where a specific type of Advice should be applied. To achieve this we use Pointcut.
We can use class names, method names or regular expressions to specify the Pointcuts for an Advice.

73. What is an Introduction in Spring AOP?
In Spring AOP we can declare additional methods or fields on behalf of a type. To do this we use an Introduction. It is also known as inter-type declaration.
E.g. We can use an Introduction for making a bean implement IsModified interface.

74. What is a Target object in Spring AOP?
A Target object is the object that gets Advice from one or more Aspects. This is also known as advised object.
In most cases it is a proxy object.

75.What is a Proxy in Spring AOP?
In Spring AOP, a Proxy is an object created by the AOP framework to implement Aspect contracts. It is generally a JDK dynamic proxy or CGLIB proxy.

76. What are the different types of AutoProxy creators in Spring?
Spring AOP provides following standard types of Autoproxy creators:

  1. BeanNameAutoProxyCreator: This is a BeanPostProcessor that creates AOP proxies for beans automatically by matching names.
  2. DefaultAdvisorAutoProxyCreator: This creator is more powerful that other Proxy Creators. This also applies eligible advisors automatically to bean in the current context.
  3. AbstractAdvisorAutoProxyCreator: This is the parent class of DefaultAdvisorAutoProxyCreator. We can create our own auto-proxy creators by extending this class.

77. What is Weaving in Spring AOP?
In Aspect oriented programming, linking Aspects with the other application types creates an Advised object. This process is known as Weaving.
Without Weaving, we just have definition of Aspects. Weaving makes use realize full potential of the AOP.
Weaving can be done at compile time, load time or at run time.

78.In Spring AOP, Weaving is done at compile time or run time?
Spring container performs Weaving at run time.

79.What is XML Schema-based Aspect implementation?
Spring allows for implementing Aspect by using regular classes and XML based configurations. This is different from Annotation based Aspect implementation. But it achieves the same goal of AOP.
We can use elements like

in Spring XML config file.
To use this we need to import Spring AOP schema as follows:

80. What is Annotation-based aspect implementation in Spring AOP?
This is a declarative style AOP implementation. In this case, we use annotations like @Aspect, @Pointcut, @Joinpoint etc. to annotate code with different types of AOP elements.
This can be used Java 5 onwards, when the support for Annotations was introduced.

81. How does Spring MVC framework work?
Spring provides its own Model View Controller (MVC) framework for developing web applications.
Spring MVC framework is based on Inversion of Control (IOC) principle. It separates the business objects from controller.
It is designed around the DispatcherServlet that is responsible for dispatching requests to relevant handlers.
Spring MVC framework also supports annotation based binding of request parameters.

82.What is DispatcherServlet?
In Spring MVC, DispatcherServlet is the core servlet that is responsible for handling all the requests and dispatching these to handlers.
Dispatcher servlet knows the mapping between the method to be called and the browser request. It calls the specific method and combines the results with the matching JSP to create an html document, and then sends it back to browser.
In case of RMI invocation, it sends back response to the client application.

83.Can we have more than one DispatcherServlet in Spring MVC?
Yes, a Spring MVC web application can have more than one DispatcherServlets.
Each DispatcherServlet has to operate in its own namespace. It has to load its own ApplicationContext with mappings, handlers, etc.
Only the root application context will be shared among these Servlets.

84.What is WebApplicationContext in Spring MVC?
WebApplicationContext is the child of plain ApplicationContext. It is used in web applications. It provides features to deal with webrelated components like- controllers, view resolvers etc. A Web Application can have multiple WebApplicationContext to handle requests.
Each DispatcherServlet is associated with one WebApplicationContext.

85.What is Controller in Spring MVC framework?

Spring Interview Questions and Answers

Controller is an interface in Spring MVC. It receives HttpServletRequest and HttpServletResponse in web app just like an HttpServlet, but it is able to participate in an MVC flow.
Controllers are similar to a Struts Action in a Struts based Web application.
Spring recommends that the implementation of Controller interface should be a reusable, thread-safe class, capable of handling multiple HTTP requests throughout the lifecycle of an application.
It is preferable to implement Controller by using a JavaBean. Controller interprets user input and transforms it into a model. The model is represented to the user by a view.
Spring implements a controller in a very generic way. This enables us to create a wide variety of controllers.
What is @Controller annotation in Spring MVC?
We use @ Controller annotation to indicate that a class is a Controller in Spring MVC.
The dispatcher in Spring scans for @Controller annotated classes for mapped methods and detects @RequestMapping.

86. What is @RequestMapping annotation in Spring?
In Spring MVC, we use @RequestMapping annotation to map a web request to either a class or a handler method.
In @RequestMapping we can specify the path of URL as well as HTTP method like- GET, PUT, POST etc.
@RequestMapping also supports specifying HTTP Headers as attributes.
We can also map different media types produced by a controller in  @RequestMapping. We use HTTP Header Accepts for this purpose.

87.What are the main features of Spring MVC?
Spring MVC has following main features:

1. Clear separation of role: In Spring MVC, each role   like-   controller, validator, command object, form
object, model object, DispatcherServlet, handler mapping, view resolver etc. is fulfilled by a specialized object.
2. Reusability: Spring MVC promotes reusable business code that reduces the need for duplication. We can use existing business objects as command or form objects instead of copying them to extend a particular framework base class.
3. Flexible Model Transfer: Spring MVC Model transfer supports easy integration with other view technologies as well.
4. Customizable binding and validation: In Spring MVC, we can to custom binding between Requests and Controllers. Even validation can be done on non-String values as well.
5. JSP form tag library: From Spring 2.0, there is a powerful JSP form tag library that makes writing forms in JSP pages much easier.
6. Customizable locale, time zone and theme resolution: Spring MVC supports customization in locale, timezone etc.

88. What is the difference between a Singleton and Prototype bean in Spring?
Every bean in Spring has a scope that defines its existence timeframe in the application.
Singleton scope for bean limits a bean to a single object instance per Spring IOC container.
This single instance is limited to a specific ApplicationContext. If there are multiple ApplicationContext then we can have more than one instance of bean.
By default all the beans in Spring framework are Singleton scope beans.
With Prototype scope a single bean definition can have multiple object instances in a Spring container.
In prototype scope bean, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made.

89.How will you decide which scopePrototype or Singleton to use for a bean in Spring?
In general, we use prototype scope for all stateful beans and singleton scope for stateless beans.
Since a stateless bean does not maintain any state, we can use the same object instance again and again. Singleton scope bean serves the same purpose.
In a stateful bean, there is a need to maintain the state in each request, it is necessary to use a new instance of object with each call. A Prototype scope bean ensures that we get a new instance each time we request for the object.

90. What is the difference between Setter and Constructor based Dependency Injection (DI) in Spring
Main differences between Setter and Constructor based Dependency Injection (DI) in Spring are:
Priority: Setter based injection has higher priority than a constructor based injection in Spring. If an  application uses Setter as well as Constructor injection, Spring container uses the Setter injection.
Partial dependency: We can inject partial dependency by using Setter injection. In Constructor injection, it is not possible to do just a partial dependency injection.
E.g. If there are two properties in a class, we can use Setter method to inject just one property in the class.
Flexibility: Setter injection gives more flexibility in introducing changes. One can easily change the value by Setter injection. In case of Constructor injection a new bean instance has to be created always.
Readability: Setter injection is more readable than Constructor injection. Generally Setter method name is similar to dependency class being used in setter method.

91.What are the drawbacks of Setter based Dependency Injection (DI) in Spring?
Although Setter based Dependency Injection has higher priority than Constructor based DI, there are some disadvantages of it.
No Guarantee: In Setter based DI, there is no guarantee that a certain dependency is injected or not. We may have an object with partial or no dependency. Whereas in Constructor based DI, an object in not created till the time all the dependencies are ready.
Security: One can use Setter based DI to override another dependency. This can cause Security breach in a Spring application.
Circular Dependency: Setter based DI can cause circular dependency between objects. Where as Constructor based DI will throw ObjectCurrentlyInCreationException if there is a circular dependency during the creation of an object.

92. What are the differences between Dependency Injection (DI) and Factory Pattern?
Main differences between Dependency Injection (DI) and Factory Pattern are:
Coupling: Factory pattern adds tight coupling between an object, factory and dependency. In case of DI, there is no coupling between objects. We just mention the dependencies on different objects and container resolves and introduces these dependencies.
Easier Testing: DI is easier to test, since we can inject the mock objects as dependency in Test environment. In case of Factory pattern, we need to create actual objects for testing.
Flexibility: DI allows for switching between different DI frameworks easily. It gives flexibility in the choice of DI framework.
Container: DI always needs a container for injecting the dependencies. This leads to extra overhead as well as extra code in your application. In factory pattern, you can just use POJO classes to implement the application without any container.
Cleaner Code: DI code is much cleaner than Factory pattern based code. In DI, we do not need to add extra code for factory methods.

93.In Spring framework, what is the difference between FileSystemResource and ClassPathResource?
In Spring we can specify configuration by using a file or classpath.
In FileSystemResource we have to give absolute path / relative path of Spring Configuration file spring-config.xml file.
In ClassPathResource Spring looks for Spring Configuration file spring-config.xml in ClassPath. Therefore, developer has to include spring-config.xml in classpath.
ClassPathResource looks for configuration file in CLASSPATH, whereas FileSystemResource looks for configuration file in file system.

94. Name some popular Spring framework annotations that you use in your project?
Spring has many Annotations to serve different purposes. For regular use we refer following popular Spring annotations:
@Controller: This annotation is for creating controller classes in a Spring MVC project.
@RequestMapping: This annotation maps the URI to a controller handler method in Spring MVC.
@ResponseBody: For sending an Object as response we use this annotation.
@PathVariable: To map dynamic values from a URI to handler method arguments, we use this annotation.
@Autowired: This annotation indicates to Spring for auto-wiring dependencies in beans.
@Service: This annotation marks the service classes in Spring.
@Scope: We can define the scope of Spring bean by this annotation.
@Configuration: This an annotation for Java based Spring configuration.
@Aspect, @Before, @After, @Around, @Joinpoint, @Pointcut: These are the annotations in Spring for AspectJ AOP.

95. How can you upload a file in Spring MVC Application?
In Spring MVC framework we can use MultipartResolver interface to upload a file. We need to make configuration changes to make it work. After uploading the file, we have to create Controller handler method to process the uploaded file in application.

96. What are the different types of events provided by Spring framework?
Spring framework provides following five events for Context:
ContextRefreshedEvent: Whenever ApplicationContext is initialized or refreshed, Spring publishes this event. We can also raise it by using refresh() method on ConfigurableApplicationContext interface.
ContextStartedEvent: When ApplicationContext is started using start() method on ConfigurableApplicationContext interface, ContextStartedEvent is published. We can poll database or restart
any stopped application after receiving this event.
ContextStoppedEvent: Spring publishes this event when ApplicationContext is stopped using stop() method on ConfigurableApplicationContext interface. This is used for doing any cleanup work.
ContextClosedEvent: Once the ApplicationContext is closed using close() method, ContextClosedEvent is published. Once a context is closed, it is the last stage of its lifecycle. After this it cannot be refreshed or restarted.
RequestHandledEvent: This is a web specific event that informs to all beans that an HTTP request has been serviced.

97. What is the difference between DispatcherServlet and ContextLoaderListener in Spring?
DispatcherServlet is the core of Spring MVC application. It loads Spring bean configuration file and initialize all the beans mentioned in config file.
In case we have enabled annotations in Spring config file, it also scans the packages and configures any bean annotated with @Component, @Controller, @Repository or @Service annotations.
ContextLoaderListener is a listener to start up and shut down Spring’s root WebApplicationContext. ContextLoaderListener links the lifecycle of ApplicationContext to the lifecycle of the
ServletContext. It automates the creation of ApplicationContext. It can also be used to define shared beans used across different spring contexts.

98. How will you handle exceptions in Spring MVC Framework?
Spring MVC Framework provides following mechanisms to help us achieve exception handling:
Controller Based: A developer can define exception handler methods in a Controller class. To do so, they have to annotate the methods with @ExceptionHandler annotation.
Global Exception Handler: Spring provides @ControllerAdvice annotation for exception handling as cross-cutting concern. We can mark any class as global exception handler by using this annotation.
HandlerExceptionResolver implementation: Spring Framework provides HandlerExceptionResolver interface that can be implemented to create a global exception handler.

99. What are the best practices of Spring Framework?
In Spring Framework, following are some of the best practices:
We can Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
It is better to avoid version numbers in schema reference. This makes sure that we have the latest config files.
It is a good practice to configure bean dependencies as much as possible. Unless there is a good reason, we try to avoid autowiring. For spring beans that are used in multiple contexts in Spring MVC, we can create them in root context and initialize with listener.
Spring framework provides many features and modules. We should just use what we need for our application. An extra dependency has to be removed
For application properties, it is good to create a property file and read it in Spring configuration file.
Annotations are useful for smaller applications, but for larger applications annotations can become an overhead. It is easier to maintain if all the configurations are in xml files.
When we are doing AOP, we have to make sure to keep the Joinpoint as narrow as possible to avoid Advice on unwanted methods.
We should use right annotation for components or services. For services use @Service and for DAO beans use @Repository. Dependency Injection (DI) has to be used when there is real benefit. It should not be used just for the sake of loose coupling.

100. What is Spring Boot?

Spring Boot is a ready made solution to create Spring applications with production grade features. It favors convention over configuration.
We can embed Tomcat or Jetty in in an application created with Spring Boot. Spring Boot automatically configures Spring in an application.
It does not require any code generation or xml configuration. It is an easy solution to create applications that can run stand-alone.

That’s all about Spring Interview Questions and Answers. You might study more about the Spring framework tutorials


Spring Framework

Please share it if you found this useful
Hide Buttons