InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What will be the selection state of a checkbox input if the user first checks the checkbox and gets validation errors in other fields and then unchecks the checkbox after getting the errors? |
|
Answer» The validation is generally performed during HTTP POST requests. During HTTP requests, 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. Conclusion:In this article, we have seen the most commonly asked Spring INTERVIEW Questions during an interview. Spring is a very powerful framework that allows building enterprise-level web applications. 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. |
|
| 2. |
How is it possible to use the Tomcat JNDI DataSource in the Spring applications? |
|
Answer» 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: <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/MySQLDB"/></bean> |
|
| 3. |
What do you understand by MultipartResolver? |
|
Answer» 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: |
|
| 4. |
How are i18n and localization supported in Spring MVC? |
|
Answer» 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:
Syntax: <bean id="localeResolver"class="org.Springframework.web.servlet.i18n.SessionLocaleResolver"> <property name="defaultLocale" value="en" /></bean>
Syntax: <bean id="localeChangeInterceptor"class="org.Springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang" /></bean>
Syntax: <bean class="org.Springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <ref bean="localeChangeInterceptor" /> </list> </property></bean> |
|
| 5. |
Differentiate between a Bean Factory and an Application Context. |
|||||||||||||||
|
Answer» 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:
|
||||||||||||||||
| 6. |
How to get ServletConfig and ServletContext objects in spring bean? |
|
Answer» This can be DONE by either implementing the spring-aware INTERFACES or by using the @Autowired ANNOTATION. @Autowiredprivate SERVLETCONTEXT servletContext;@Autowiredprivate SERVLETCONFIG servletConfig; |
|
| 7. |
How is the form data validation done in Spring Web MVC Framework? |
|
Answer» 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. @Componentpublic class UserValidator implements Validator{ public boolean SUPPORTS(Class clazz) { return UserVO.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name", "Name is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "error.age", "Age is required."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "error.phone", "Phone is required."); }}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:
OR The validator class can be registered in the context file directly as a bean as shown: <bean id="userValidator" class="com.interviewbit.validators.UserValidator" /> |
|
| 8. |
What are the differences between the vs tags? |
|
Answer» <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.
|
|
| 9. |
Is there any need to keepspring-mvc.jar on the classpath or is it already present as part of spring-core? |
|
Answer» 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. |
|
| 10. |
What are Spring Interceptors? |
|
Answer» 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 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. |
|
| 11. |
Why do we need BindingResults? |
|
Answer» 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: @PostMapping("/interviewbit")public String registerCourse(@Valid RegisterUser registerUser, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { RETURN "home"; } model.addAttribute("message", "Valid inputs"); return "home";}The Spring will understand to FIND the corresponding VALIDATORS by checking the @Valid annotation on the parameter. |
|
| 12. |
Where does the access to the model from the view come from? |
|
Answer» 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. |
|
| 13. |
How does the Spring MVC flow look like? In other words, How does a DispatcherServlet know what Controller needs to be called when there is an incoming request to the Spring MVC? |
|
Answer» 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. |
|
| 14. |
How is the root application context in Spring MVC loaded? |
|
Answer» 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. |
|
| 15. |
How is the dispatcher servlet instantiated? |
|
Answer» 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: <?xml VERSION="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Define Dispatcher Servlet --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>InterviewBitServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>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 initializes BEANS that are defined in the file. |
|
| 16. |
What is the significance of @Repository annotation? |
|
Answer» @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. |
|
| 17. |
How can you achieve thread-safety in beans? |
|
Answer» 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. |
|
| 18. |
Are singleton beans thread-safe? |
|
Answer» 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. |
|
| 19. |
Differentiate between the @Autowired and the @Inject annotations. |
||||||||||||
Answer»
|
|||||||||||||
| 20. |
What is the importance of @Required annotation? |
|
Answer» 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: import org.Springframework.beans.factory.annotation.Required;PUBLIC class USER { private INT age; private String name; @Required public void setAge(int age) { this.age = age; } public Integer getAge() { return this.age; } @Required public void setName(String name) { this.name = name; } public String getName() { return this.name; }} |
|
| 21. |
What is the importance of session scope? |
|
Answer» Session scopes are used to create BEAN INSTANCES for HTTP sessions. 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.
|
|
| 22. |
What are the types of Spring MVC Dependency Injection? |
|
Answer» There are two types of DI (Dependency Injection):
Annotation Configuration: This approach USES POJO objects and annotations for configuration. For example, consider the below code snippet: @Configuration@ComponentScan("com.interviewbit.constructordi")public class SpringAppConfig { @Bean public Shape shapes() { return new Shapes("Rectangle"); } @Bean public Dimension dimensions() { return new Dimension(4,3); }}Here, the annotations are used for notifying the Spring runtime that the class specified with @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: @Componentpublic class Figure { private Shape shape; private Dimension dimension; @Autowired public Figure(Shape shape, Dimension dimension) { this.shape = shape; this.dimension = dimension; }}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: ApplicationContext context = new AnnotationConfigApplicationContext(SpringAppConfig.class);Figure figure = context.getBean(Figure.class);XML Configuration: This is another way of configuring Spring runtime by using the XML configuration file. For example, consider the below code snippet in the springAppConfig.xml file: <bean id="toyota" class="com.interviewbit.constructordi.Figure"> <constructor-arg index="0" ref="shape"/> <constructor-arg index="1" ref="dimension"/></bean><bean id="shape" class="com.interviewbit.constructordi.Shape"> <constructor-arg index="0" value="Rectangle"/></bean><bean id="dimension" class="com.interviewbit.constructordi.Dimension"> <constructor-arg index="0" value="4"/> <constructor-arg index="1" value="3"/></bean>The 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.
In the bean configuration file, we will be setting as below: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="InterviewBit" class="com.interviewbit.model.InterviewBit"> <property name="article"> <ref bean="JsonArticle" /> </property> </bean> <bean id="JsonArticle" class="com.interviewbit.bean.JsonArticle" /></beans>The ‘JsonArticle’ bean is injected into the InterviewBit class object by means of the setArticle method. |
|
| 23. |
What is the importance of the web.xml in Spring MVC? |
|
Answer» 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. |
|
| 24. |
What is the role of @ModelAttribute annotation? |
|
Answer» The annotation plays a very important role in binding method parameters 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. |
|
| 25. |
What is the use of @Autowired annotation? |
|
Answer» @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: import org.Springframework.beans.factory.annotation.Autowired;import java.util.*;public class InterviewBit { // Autowiring/Injecting FormatterUtil as dependency to InterviewBit class @Autowired private FormatterUtil formatterUtil; public Date something( String value ){ Date dateFormatted = formatterUtil.formatDate(value); RETURN dateFormatted }}/*** Util class to format any string value to valid date format*/public class FormatterUtil { public Date formatDate(String value){ //code to format date }} |
|
| 26. |
What is the Model in Spring MVC? |
Answer»
|
|
| 27. |
What are the differences between @RequestParam and @PathVariable annotations? |
Answer»
|
|
| 28. |
What is ContextLoaderListener and what does it do? |
Answer»
|
|
| 29. |
Can you create a controller without using @Controller or @RestController annotations? |
Answer»
|
|
| 30. |
What is the @Controller annotation used for? |
Answer»
|
|
| 31. |
What is a View Resolver pattern and explain its significance in Spring MVC? |
Answer»
|
|
| 32. |
What is DispatcherServlet in Spring MVC? In other words, can you explain the Spring MVC architecture? |
|
Answer» Spring MVC framework is built around a central servlet CALLED DispatcherServlet that handles all the HTTP requests and responses. The DispatcherServlet does a lot more than that:
|
|
| 33. |
What are the benefits of Spring MVC framework over other MVC frameworks? |
Answer»
|
|
| 34. |
What is the Spring MVC framework? |
Answer»
|
|