Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

15 Must-Know Spring MVC Interview Questions

The document discusses 15 must-know Spring MVC interview questions, including questions about the Spring framework, Spring MVC, dependency injection, validation, scopes, and more.

Uploaded by

Rahul Pawar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

15 Must-Know Spring MVC Interview Questions

The document discusses 15 must-know Spring MVC interview questions, including questions about the Spring framework, Spring MVC, dependency injection, validation, scopes, and more.

Uploaded by

Rahul Pawar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

15 Must-Know Spring MVC Interview

Questions

In this article, we’ll be talking about 15 such Spring MVC


must-know questions which you can expect to encounter
in any interview you sit for.

1. What is the Spring framework?

Spring is an open-source framework that was built to simplify application development.


It has a layered structure which allows the developer to be selective about the
components they use. It has three main components - Spring Core, Spring AOP, and
Spring MVC.

Further, you can talk about your experience with Spring, if any. That’ll add a lot of weight
to your answer.

2. What are the main features of Spring framework?


Spring framework offers a lot of features to make the developer’s life easy. Some of
them are:

1. Lightweight: Spring is extremely lightweight, the basic version is around 1MB,


with negligible processing overheads.
2. Inversion of Control (IoC): Dependency Injection or Inversion of Control is one of
the most important features of Spring. Using IoC, the developers don’t need to
create the complete environment for the object and its dependencies; they can
simply create and test the object they are handling at the given point of time.
Object dependencies will be included or called upon when the need arises.
3. Aspect Oriented Programming: Spring supports Aspect Oriented Programming.
AOP isolates secondary functions from the programmer’s business logic. This
not only provides modularity but also makes the code maintainable.
4. MVC architecture: Spring comes with an MVC framework for web-applications.
This framework is highly configurable using various technologies like JSP, Tiles,
iText, and POI.
5. JDBC exception handling: Spring comes with a predefined JDBC abstraction
layer which simplifies the overall exception handling process.

3. Explain a bit more about Dependency Injection.


Inversion of Control or Dependency Injection aims to simplify the process of object
creation by following a simple concept - don’t create objects, just describe how they
should be created. Using IoC, the objects are given their dependencies at build-time by
an external entity that is responsible for coordinating each object in the system. In
essence, we’re injecting dependencies into objects using IOC or Dependency Injection.

4. Explain the different types of Dependency Injections in Spring? When to use


which?
Spring provides the developers with the following two types of dependency injections:

1. Constructor-based DI: Constructor-based DI is accomplished by passing a


number of arguments (each of which represents a dependency on other class) to
a class’s constructor. Simply, dependencies are given in the form of constructor
parameters.
2. Setter-based DI: When you are working with a no-argument constructor, you will
set values by passing arguments through setter function to instantiate the bean
under consideration, this is called setter-based dependency injection.
3. Field or Property-Based Dependency Injection:
When the annotation @Autowired is used on top of the field or property in the class, it is
referred to as Field-based Dependency Injection. Let us witness the usage of
Field-based Dependency Injection with a real-time example.
When will you use which one of these, boils down to your requirements. However, it is
recommended to use Setter-based DI for optional dependencies and Constructor-based
DI for mandatory dependencies.

5. What is the Spring MVC framework?


Spring MVC is one of the core components of the Spring framework. It comes with
ready to use components and elements that help developers build flexible and robust
web applications. As the name suggests, the MVC architecture separates the different
aspects of the application - input logic, business logic, and UI logic. It also provides a
loose coupling between the M, V, and C of the application.

6. What are some benefits of Spring MVC framework over other MVC
frameworks?
The Spring MVC framework has some clear benefits over other frameworks. Some of
the benefits are:

1. Clear separation of roles – There is a specialised object for every role, thus
providing a clear separation of roles.
2. Reusable business code – With Spring MVC, you don’t need to duplicate your
code. You can use your existing objects as commands instead of mirroring them
in order to extend a particular framework base class.
3. Customizable binding and validation
4. Customizable locale and theme resolution
5. Customizable handler mapping and view resolution
6. From Spring 2.0 onwards, the framework comes with a JSP form tag library
which makes writing forms in JSP pages much easier.

7. What is DispatcherServlet?
Spring MVC framework is request-driven and is designed around a central Servlet that
handles all the HTTP requests and responses. The DispatcherServlet, however, does a
lot more than just that. It seamlessly integrates with the IoC container and allows you to
use each feature of Spring.

On receiving an HTTP request, the DispatcherServlet consults HandlerMapping (these


are the configuration files) to call the appropriate Controller. Then, the controller calls
appropriate service methods to set the Model data. It also returns the view name to
DispatcherServlet. DispatcherServlet, with the help of ViewResolver, picks up the
defined view for the request. Once the view is finalised, the DispatcherServlet passes
the Model data to View - where it is finally rendered on the browser.

8. What is the front controller class of the Spring MVC?


A front controller is a controller which handles all requests for a Web application. When
it comes to Spring MVC, DispatcherServlet is that front controller. When a web request
is sent to a Spring MVC application, the DIspatcherServlet takes care of everything.
First, it takes the request. Then, it organises the different components like request
handlers, controllers, view resolvers, and such - all needed to handle the request. And
finally, it renders the content on the browser.

9. What is a Viewresolver pattern and how does it work in MVC?


View Resolver is a J2EE pattern which allows the applications to dynamically choose a
technology for rendering the data on the browser (View). Any technology like HTML,
JSP, Tapestry, XSLT, JSF, or any other such technology can be used for View. The View
Resolver pattern holds the mapping of different views. The Controller returns the name
of the View which is then passed to View Resolver for selecting the appropriate
technology.

10. How does Spring MVC provide validation support?


Spring primarily supports two types of validations:

1. Using JSR-303 Annotations and any reference implementation, for example,


Hibernate Validator, or
2. Implementing org.springframework.validation.Validator interface.

11. A user gets a validation error in other fields on checking a checkbox, after
which, he unchecks it. What would be the current selection status in command
object of the Spring MVC? How will you fix this issue?
This is one of the trickier questions to answer if you aren’t aware of the HTTP Post
behaviour in Spring MVC.

During HTTP Post, if you uncheck the checkbox, then HTTP does not include a request
parameter for the checkbox - which means the updated selection won’t be picked up. To
fix that, you can use hidden form field which starts with ‘_’.

12. How will you compare the MVC framework to the three-tier architecture?
A Three-tier architecture is an architecture style whereas MVC is a design pattern.

Having said that, in larger applications, MVC forms the presentation tier of a three-tier
architecture. The Model, View, and Controller are concerned only with the presentation -
they use the middle tier to populate their models.
13. How should we use JDBC in Spring to optimise the performance?
Spring provides a template class called as JDBCTemplate. Using JDBC with this
template gives manifolds better performance.

14. What do you mean by a “Bean” in the context of Spring framework?


Any class that is initialised by the IoC container is known as a bean in Spring. The
lifecycle of a Spring Bean is managed by Spring IoC Container.

15. What is a “Scope” in reference to Spring Beans?


Spring Beans comes with following five scopes:

1. Prototype: Whenever there’s a request for a bean, a separate prototype is


created each time.
2. Request: It is like the previous scope, but only for web-based applications. For
each HTTP request, Spring creates a new bean instance.
3. Singleton: There’s only one bean created for every container, and it acts as the
default scope of that bean. In all these instances, the beans cannot use a shared
instance variable as it can lead to data-inconsistency.
4. Session: A bean is created for every HTTP session.
5. Global-session: Global session is created for Portlet applications.

The Spring framework is extendable, that is, you can create your own scope as well.
The “scope” attribute of the bean element is used to define the scope.

Wrapping Up…
@ComponentScan: It is used when we want to scan a package for beans.

@Component: It is a class-level annotation. It is used to mark a Java class as a bean.

@Controller: The @Controller is a class-level annotation. It marks a class as a web


request handler. It is often used to serve web pages.

@Service: It is also used at class level. It tells the Spring that class contains the
business logic.

@RequestMapping: It is used to map web requests.

@Repository: It is a class-level annotation. Provide the mechanism for storage, retrieval,


search, update and delete operations on objects.

@PostMapping: It maps the HTTP POST requests on the specific handler method.

singleton scope. singleton is default bean scope in spring container. It tells the
container to create and manage only one instance of bean class, per container. This
single instance is stored in a cache of such singleton beans, and all subsequent
requests and references for that named bean return the cached instance.
Spring Spring Boot

1. Spring framework helps to create a loosely Spring Boot helps to


coupled application. create a stand-alone
application.

2. In the Spring framework, you have to build There is no need to build


configurations manually. configuration manually.
(i.e autoconfiguration)
Spring Boot
autoconfiguration is a
method of automatically
configuring a Spring
application based on the
dependencies found on
the classpath

3. Spring Framework is a widely used Java EE Spring Boot Framework is


framework for building applications. widely used to develop
REST APIs

4. To test the Spring project, we need to set up the Spring Boot offers
server explicitly. embedded servers such as
Jetty and Tomcat, etc.

@PathVariable
@PathVariable is a Spring annotation which indicates that a method parameter
should be bound to a URI template variable.
It has the following optional elements:

● name - name of the path variable to bind to

● required - tells whether the path variable is required

● value - alias for name

package com.zetcode.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

@RequestMapping(path="/{name}/{age}")
public String getMessage(@PathVariable("name") String name,
@PathVariable("age") String age) {

var msg = String.format("%s is %s years old", name, age);

return msg;
}
}

@RequestParam

@RequestParam - it is used with query parameter

@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam String id) {
return "ID: " + id;
}
we used @RequestParam to extract the id of query parameter.

http://localhost:8080/spring-mvc-basics/api/foos?id=abc
----
ID: abc

Spring Component annotation is used to denote a class as Component. It means that


Spring framework will autodetect these classes for dependency injection when
annotation-based configuration and classpath scanning is used.

You might also like