The Spring Framework was first developed by Rod Johnson in 2003. It was developed to make the development of Java applications quicker, easier and safer for developer. Spring Framework is an open-source, lightweight, easy to build a framework that can also be considered as a framework of frameworks as it houses various frameworks like Dependency Injection, Spring MVC, Spring JDBC, Spring Hibernate, Spring AOP, EJB, JSF etc. A key element of Spring is the feature of application's infrastructural support. Spring focuses on providing the "plumbing" of enterprise-level applications and ensures that the developers can focus purely on application-level business logic, without unnecessary ties to specific deployment environments. Applications developed in Spring are more reliable, scalable and very simple to build and maintain. Spring was developed as means to help developers manage the business objects of the application. Due to its vast features and flexibilities, Spring became the most loved framework for developing enterprise-level Java-based applications. In the following section, we will see what are the most commonly asked interview questions and their answers to prepare you for Spring-based interviews.
@Autowired
annotation?@Autowired
annotation is meant for the injection of a bean by means of its type along with methods and fields. This helps the Spring framework to resolve dependencies by injecting and collaborating the beans into another bean. For example, consider the below code snippet:
The annotation plays a very important role in binding method parameter to the respective attribute that corresponds to a model. Then it reflects the same on the presentation page. The role of the annotation also depends on what the developer is using that for. In case, it is used at the method level, then that method is responsible for adding attributes to it. When used at a parameter level, it represents that the parameter value is meant to be retrieved from the model layer.
web.xml
in Spring MVC?web.xml
is also known as the Deployment Descriptor which has definitions of the servlets and their mappings, filters and lifecycle listeners. It is also used for configuring the ContextLoaderListener. Whenever the application is deployed, a ContextLoaderListener instance is created by Servlet container which leads to a load of WebApplicationContext.
There are two types of DI (Dependency Injection):
@Bean
annotation is the provider of beans and the process of context scan needs to be performed on the package com.interviewbit.constructordi
by means of @ComponentScan
annotation. Next we will be defining a Figure class component as below:
Spring encounters this Figure class while performing context scan and it initializes the instance of this class by invoking the constructor annotated with @Autowired
. The Shape and Dimension instances are obtained by calling the methods annotated with @Bean
in the SpringAppConfig
class. Instances of Engine and Transmission will be obtained by calling @Bean annotated methods of the Config class. Finally, we need to bootstrap an ApplicationContext using our POJO configuration:
constructor-arg
tag can accept either literal value or another bean's reference and explicit index and type. The index and type arguments are used for resolving conflicts in cases of ambiguity.ApplicationContext
needs to use ClassPathXmlApplicationContext
as shown below:
<property>
tag. For example, consider a class InterviewBit
that sets the property articles
as shown below:
In the bean configuration file, we will be setting as below:
The ‘JsonArticle’ bean is injected into the InterviewBit class object by means of the setArticle
method.In cases where both types of dependencies are used, then the setter dependency injection has more preference by considering the specificity nature.
Session scopes are used to create bean instances for HTTP session. This would mean that a single bean can be used for serving multiple HTTP requests. The scope of the bean can be defined by means of using scope attribute or using @Scope or @SessionScope annotations.
<bean id="userBean" class="com.interviewbit.UserBean" scope="session"/>
The annotation is used for indicating that the property of the bean should be populated via autowiring or any explicit value during the bean definition at the configuration time. For example, consider a code snippet below where we need to have the values of age and the name:
@Autowired | @Inject |
---|---|
This annotation is part of the Spring framework. | This annotation is part of Java CDI. |
Has required attribute. | Does not have the required attribute. |
Singleton is the default scope for autowired beans. | Prototype is the default scope of inject beans. |
In case of ambiguity, then @Qualifier annotation is to be used. | In case of ambiguity, then @Named qualifier needs to be used. |
Since this annotation is provided by the Spring framework, in case you shift to another Dependency injection framework, there would be a lot of refactoring needed. | Since this annotation is part of Java CDI, it is not framework dependent and hence less code refactoring when there are framework changes. |
No, the singleton beans are not thread-safe because the concept of thread-safety essentially deals with the execution of the program and the singleton is simply a design pattern meant for the creation of objects. Thread safety nature of a bean depends on the nature of its implementation.
The thread safety can be achieved by changing the scope of the bean to request, session or prototype but at the cost of performance. This is purely based on the project requirements.
@Repository annotation indicates that a component is used as the repository that acts as a means to store, search or retrieve data. These can be added to the DAO classes.
The dispatcher servlet is instantiated by means of servlet containers such as Tomcat. The Dispatcher Servlet should be defined in web.xml
The DispatcherServlet is instantiated by Servlet containers like Tomcat. The Dispatcher Servlet can be defined in web.xml
as shown below:
Here, the load-on-startup tag is 1 which indicates that the DispatcherServlet is instantiated whenever the Spring MVC application to the servlet container. During this process, it looks for the servlet-name-context.xml file and initialises beans that are defined in the file.
The root application context is loaded using the ContextLoaderListener that belongs to the entire application. Spring MVC allows instantiating multiple DispatcherServlet and each of them have multiple contexts specific to them. They can have the same root context too.
A Dispatcher Servlet knows which controller to call by means of handler mappings. These mappings have the mapping between the controller and the requests. BeanNameUrlHandlerMapping
and SimpleUrlHandlerMapping
are the two most commonly used handler mappings.
If the Spring MVC is configured using annotations, then @RequestMapping annotations are used for this purpose. The @RequestMapping annotation is configured by making use of the URI path, HTTP methods, query parameters and the HTTP Headers.
The view requires access to the model to render the output as the model contains the required data meant for rendering. The model is associated with the controller that processes the client requests and finally encapsulates the response into the Model object.
BindingResults is an important Spring interface that is within the org.Springframework.validation
package. This interface has a very simple and easy process of invocation and plays a vital role in detecting errors in the submitted forms. However, care has to be taken by the developer to use the BindingResult parameter just after the object that needs validation. For example:
The Spring will understand to find the corresponding validators by checking the @Valid annotation on the parameter.
Spring Interceptors are used to pre-handle and post-handle the web requests in Spring MVC which are handled by Spring Controllers. This can be achieved by the HandlerInterceptor
interface. These handlers are used for manipulating the model attributes that are passed to the controllers or the views.
The Spring handler interceptor can be registered for specific URL mappings so that it can intercept only those requests. The custom handler interceptor must implement the HandlerInterceptor
interface that has 3 callback methods that can be implemented:
The only problem with this interface is that all the methods of this interface need to be implemented irrespective of its requirements. This can be avoided if our handler class extends the HandlerInterceptorAdapter
class that internally implements the HandlerInterceptor
interface and provides default blank implementations.
spring-mvc.jar
on the classpath or is it already present as part of spring-core?The spring-mv.jar
does not belong to the spring-core. This means that the jar has to be included in the project's classpath if we have to use the Spring MVC framework in our project. For Java applications, the spring-mvc.jar
is placed inside /WEB-INF/lib
folder.
<context:annotation-config>
vs <context:component-scan>
tags?<context:annotation-config>
is used for activating applied annotations in pre-registered beans in the application context. It also registers the beans defined in the config file and it scans the annotations within the beans and activates them.
The <context:component-scan>
tag does the task of <context:annotation-config>
along with scanning the packages and registering the beans in the application context.
<context:annotation-config>
= Scan and activate annotations in pre-registered beans.
<context:component-scan>
= Register Bean + Scan and activate annotations in package.
Spring MVC does the task of data validation using the validator object which implements the Validator interface. In the custom validator class that we have created, we can use the utility methods of the ValidationUtils class like rejectIfEmptyOrWhitespace()
or rejectIfEmpty()
to perform validation of the form fields.
In the fields that are subject to validation, in case of errors, the validator methods would create field error and bind that to the field.
To activate the custom validator as spring bean, then:
<context:component-scan base-package="com.interviewbit.validators"/>
<bean id="userValidator" class="com.interviewbit.validators.UserValidator" />
This can be done by either implementing the spring-aware interfaces or by using the @Autowired
annotation.
BeanFactory and the ApplicationContext are both Java interfaces. The difference is that the ApplicationContext extends the BeanFactory. BeanFactory provides both IoC and DI basic features whereas the ApplicationContext provides more advanced features. Following are the differences between these two:
Category | BeanFactory | ApplicationContext |
---|---|---|
Internationalization (i18n) | Does not provide support for i18n. | Provides support for i18n. |
Event Publishing | Provides the ability to publish events to listener beans by using ContextStartedEvent and ContextStoppedEvent to publish context when it is started and stopped respectively. | ApplicationContext supports event handling by means of the ApplicationListener interface and ApplicationEvent class. |
Implementations | XMLBeanFactory is a popular implementation of BeanFactory. | ClassPathXmlApplicationContext is a popular implementation of ApplicationContext. Also, Java uses WebApplicationContext that extends the interface and adds getServletContext() method. |
Autowiring | For autowiring, beans have to be registered in the AutoWiredBeanPostProcessor API. | Here, XML configuration can be done to achieve autowiring. |
Spring MVC has LocaleResolver
that supports i18n and localization. for supporting both internationalization and localization. The following beans need to be configured in the application:
The MultipartResolver is used for handling the file upload scenarios in the Spring web application. There are 2 concrete implementations of this in Spring, they are:
To implement this, we need to create a bean with id="multipartResolver" in the application context of DispatcherServlet. Doing this ensures that all the requests handled by the DispatcherServlet have this resolver applied whenever a multipart request is detected. If a multipart request is detected by the DispatcherServlet, it resolves the request by means of the already configured MultipartResolver and the request is passed on as a wrapped/abstract HttpServletRequest. Controllers then cast this request as the MultipartHttpServletRequest
interface to get access to the Multipart files. The following diagram illustrates the flow clearly:
To use the servlet container which is configured in the JNDI (Java Naming and Directory Interface) DataSource, the DataSource bean has to be configured in the spring bean config file and then injected into the beans as dependencies. Post this, the DataSource bean can be used for performing database operations by means of the JdbcTemplate. The syntax for registering a MySQL DataSource bean:
The validation is generally performed during HTTP POST requests. During HTTP request, if the state of the checkbox is unchecked, then HTTP includes the request parameter for the checkbox thereby not picking up the updated selection. This can be fixed by making use of a hidden form field that starts with _
in the Spring MVC.
In this article, we have seen the most commonly asked Spring MVC Interview Questions during an interview. Spring is a very powerful framework that allows building enterprise-level web applications using Spring MVC. Applications developed using Spring are generally quick, scalable and transparent. Due to this, Spring has been embraced by a huge Java Developer's community thereby making it an inevitable part of any Java Developer's Job Role. Knowing Spring ensures that an added advantage is with the developers to progress steadily in their careers too.