Spring Mvc Interview Questions And Answers Pdf

1. Explain the main modules of Spring?
Spring AOP:
One of the key components of Spring is the AOP framework. AOP is used in Spring:
To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring’s transaction abstraction.
To allow users to implement custom aspects, complementing their use of OOP with AOP
Spring ORM:
The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate, and iBatis.
Spring Web:
The Spring Web module is part of Spring’s web application development stack, which includes Spring MVC.
Spring DAO:
The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
Spring Context:
This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
Spring Web MVC:
This is the Module which provides the MVC implementations for the web applications.
Spring Core:
The Core package is the most import component of the Spring Framework.
This component provides Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation, and access of the objects from your actual program logic.

2. Explain the object/relational mapping integration module?
Answer: Spring also supports using an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provides support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

3. Spring configuration file?
Answer: Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

4. What is the difference between Bean Factory and Application Context?
Answer: Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.

5. What are the different types of IoC (dependency injection)?
Answer: 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.

6. What is bean auto wiring?
Answer: The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using and elements.

7. What is the difference between concern and crosscutting concern in Spring AOP?
Answer: The Concern is a behavior we want to have in a module of an application. A Concern may be defined as the functionality we want to implement.
The cross-cutting concern is a concern which is applicable throughout the application and it affects the entire application. For example, logging, security, and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns.

8. What is Spring AOP?
Answer: Aspect-oriented Programming is a programming paradigm which is analogous to object-oriented programming. Key unit of object-oriented programming is class, similarly, key unit for AOP is Aspect. Aspect enables modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers to crosscutting concerns.

9. What are the types of IOC container in spring?
There are two types of IOC containers in spring framework.

10. What is Annotation-based container configuration?
Answer: An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. 

11. Explain different modes of auto wiring?
Answer: The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:

no: This is the default setting. Explicit bean reference should be used for wiring.
byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in the configuration file. If more than one such beans exist, a fatal exception is thrown.
constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
autodetect: Spring first tries to wire using autowire by the constructor, if it does not work, Spring tries to autowire by byType.

12. What are different modes of autowiring supported by Spring?
Answer: There are following autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection.
Default, no auto wiring, set it manually via “ref” attribute as we have done in dependency injection via setter method post.
Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file and it tries to match it with the name of a bean in the xml configuration file.
Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in the configuration file. If more than one such beans exist, a fatal exception is thrown.
byType mode in the constructor argument.
Spring first tries to wire using autowire by the constructor, if it does not work, Spring tries to autowire by byType.

13. Explain the web module?
Answer: The Spring web module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.

14. Explain the Spring MVC module?
Answer: MVC framework is provided by Spring for building web applications. Spring can easily be integrated with other MVC frameworks, but Spring’s MVC framework is a better choice since it uses IoC to provide for a clean separation of controller logic from business objects. With Spring MVC you can declaratively bind request parameters to your business objects.

15. What are the benefits of IOC?
Answer: IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications since no singletons or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive mechanism. IOC containers support eager instantiation and lazy loading of services.

16. What are the common implementations of the Application Context?
Answer: The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean configuration file must be provided to the constructor.
The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
The WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application.

17. What is Dependency Injection in Spring?
Answer: Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different ways. This concept says 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 (the IOC container) is then responsible for hooking it all up.

18. Which DI would you suggest Constructor-based or setter-based DI?
Answer: You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.

19. Which are the important beans lifecycle methods? Can you override them?
Answer: There are two important bean lifecycle methods. The first one is set up which is called when the bean is loaded into the container. The second method is the teardown method which is called when the bean is unloaded from the container.
The bean tag has two important attributes (init-method and destroy-method) with which you can define your own custom initialization and destroy methods. There are also the corresponding annotations(@PostConstruct and @PreDestroy).

20. What is Spring Java-Based Configuration?
Give some annotation example.
Java-based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations.
An example is a @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of bean definitions. Another example is the@Bean annotated method that will return an object that should be registered as a bean in the Spring application context.

21. What are different ways to configure a class as Spring Bean?
Answer: There are three different ways to configure Spring Bean.

XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean. For example:

Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. A sample configuration is:
public class MyConfiguration

public MyService getService()
return new MyService();

To get this bean from spring-context, we need to use the following code snippet:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
MyService service = ctx.getBean(MyService.class);
Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide a base package location to scan for these classes.

22. How to use Tomcat JNDI DataSource in Spring Web Application?
Answer: For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.

A sample configuration would be:

For a complete example, please refer Spring Tomcat JNDI Example.

23. How would you achieve Transaction Management in Spring?
Answer: Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and works in most of the cases.

We use to annotate a method with @Transactional annotation for Declarative transaction management. We need to configure a transaction manager for the DataSource in the spring bean configuration file.

24. What is Dependency Injection?
Answer: Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept stating that you do not create your objects manually but instead describe how they should be created. An IoC container will instantiate required classes if needed.

25. How can we inject beans in Spring?
A few different options exist:

  • Setter Injection
  • Constructor Injection
  • Field Injection
  • The configuration can be done using XML files or annotations.

26. How to Get Servlet Context and Servlet Config Objects in a Spring Bean?
You can do either by:

Implementing Spring-aware interfaces. The complete list is available here.
Using @Autowired annotation on those beans:

ServletContext servlet context;

ServletConfig servlet config;

27. What is Bean in Spring?
A normal POJO class managed by Spring IOC containter are called Spring beans. It is cored part of Spring application.

28. What is the Role of the @Qualifier Annotation?
Answer: It is used simultaneously with the @Autowired annotation to avoid confusion when multiple instances of a bean type are present.

Let’s see an example. We declared two similar beans in XML config:

29. What is the default scope of bean in Spring?
Answer: singleton is default scope of a bean in Spring. You have to explicitly change the scope of a bean if you want different scope.

30. How do you provide configuration metadata to the Spring Container?
Answer: There are three important methods to provide configuration metadata to the Spring Container:

  • XML based configuration file.
  • Annotation-based configuration
  • Java-based configuration

31. Differentiate between Bean Factory and Application Context?
BeanFactory vs ApplicationContext
BeanFactory ApplicationContext
It is an interface defined in org.springframework.beans.factory.BeanFactory It is an interface defined in org.springframework.context.ApplicationContext
It uses Lazy initialization It uses Eager/ Aggressive initialization
It explicitly provides a resource object using the syntax It creates and manages resource objects on its own
It doesn’t support internationalization It supports internationalization
It doesn’t support annotation-based dependency It supports annotation-based dependency

32. What are the different scopes of Spring Bean?
There are five scopes defined for Spring Beans.
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 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.

To set Spring bean scopes we can use “scope” attribute in bean element or @Scope annotation for annotation-based configurations.

33. What is the Spring JdbcTemplate class and how to use it?
Answer: Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate utility class that we can use to avoid boiler-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement, etc.

For JdbcTemplate example, please refer Spring JDBC Example.

34. Explain the bean scopes supported by Spring?
There are five scoped provided by the Spring Framework supports the following five scopes:

In singleton scope, Spring scopes the bean definition to a single instance per Spring IoC container.
In prototype scope, a single bean definition has any number of object instances.
In the request scope, a bean is defined as an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext.
In the session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext.
In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext.
The default scope of a Spring Bean is Singleton.

35. How to upload file in Spring MVC Application?
Answer: Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use and requires only configuration changes to get it working. Obviously we would need to write a controller handler method to handle the incoming file and process it.

36. How to validate form data in Spring Web MVC Framework?
Answer: Spring supports JSR-303 annotation-based validations as well as provide a Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.

For custom validator implementation, we need to configure it in the controller class. For a complete example, please read the Spring MVC Form Validation Example.

37. What is the default bean scope in Spring framework?
By default, a Spring Bean is initialized as a singleton.

38. How can JDBC be used more efficiently in the Spring framework?
Answer: When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the help of a template class provided by the Spring framework, which is the JDBC Template.

39. Types of the transaction management Spring support?
Answer: Spring supports two types of transaction management:

Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.

40. What are the benefits of the Spring Framework’s transaction management?
It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
It supports declarative transaction management.
It integrates very well with Spring’s various data access abstractions.

41. Which Transaction management type is more preferable?
Answer: Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

42. What are the different components of a Spring application?
A Spring application generally consists of the following components:

Interface: It defines the functions.
Bean class: It contains properties, its setter and getter methods, functions, etc.
Spring Aspect-Oriented Programming (AOP): Provides the functionality of cross-cutting concerns.
Bean Configuration File: Contains the information of classes and how to configure them.
User program: It uses the function.

43. What is Aspect, Advice, Joinpoint, and pointcut in Spring AOP?
Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name.
Joint Point: It is a point in the execution of program such as the execution of the method. In Spring AOP, a join point always represents a method execution.
Advice: Action taken by an aspect at the particular join point. For example: Before execution of getting employee name() method, put logging. So here, we are using before advice.
Pointcut: Pointcut is an expression that decides the execution of advice at the matched joint point. Spring uses the AspectJ pointcut expression language by default.

44. What is the importance of the Spring bean configuration file?
Answer: We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the instance of Spring ApplicationContext, it reads the spring bean xml file and initializes all of them. Once the context is initialized, we can use it to get different bean instances.
Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to support annotations based configurations.

Note: Browse latest Spring Interview Questions and Spring Tutorial Videos. Here you can check Spring Training details and Spring Training Videos for self learning. Contact +91 988 502 2027 for more information.

Leave a Comment