Spring Interview Questions
Spring Interview Questions
codespaghetti.com/spring-interview-questions/
SPRING
Java Spring Interview Questions, Programs and Examples to help you ace your next
Technical interview.
Table of Contents:
1/35
CHAPTER 6: Spring REST Interview Questions
Spring is one of the most popular Java EE framework. Core concepts of Spring framework
are “Dependency Injection” and “Aspect Oriented Programming”.
Spring framework can be used in plain java applications to achieve loose coupling among
different application components. This loose coupling is achieved by implementing
dependency injection.
Spring framework provides a lot of features and modules for specific tasks such as Spring
MVC and Spring JDBC.
Since it’s an open source framework with a lot of online resources and active community
members, working with Spring framework is easy and fun at same time. Some of the
features of spring framework are:
2/35
Some advantages of using Spring Framework are:
Reducing direct dependencies between different components of the application,
usually Spring IoC container is responsible for initializing resources or beans and
inject them as dependencies.
Spring framework is divided into several modules, it helps us in keeping our
application lightweight.
Reduces the amount of boiler-plate code, such as initializing objects, open/close
resources.
Spring framework support most of the Java EE features and even much more.
Writing unit test cases are easy in Spring framework because our business logic
doesn’t have direct dependencies with actual resource implementation classes.
Spring bean is a normal java class that is initialized by Spring IoC container.
Spring ApplicationContext is used to get the Spring Bean instance. And spring IoC
container manages the life cycle of Spring Bean.
Spring Bean configuration file is used to define all the beans that will be initialized by Spring
context.
When an instance of Spring ApplicationContext is created. It reads the spring bean xml file.
Once the context is initialized, it is used to get different bean instances.
-View resolvers
There are three different ways to configure Spring Bean. And here they are
A Spring bean can also be configured by using @Bean annotation. This annotation is used
with @Configuration class to configure a spring bean. for example:
4/35
@Configuration
@ComponentScan(value="com.Codespaghetti.spring.main")
public class TestConfiguration {
@Bean
public TestService getService(){
return new TestService();
}
}
In order to get this bean from spring context, we need to use following code
Spring Beans are initialized by Spring Container and all the dependencies are injected.
When spring context is destroyed, it also destroys all the initialized beans.
This works well in most of the cases but sometimes we want to initialize other resources or
do some validation before making our beans ready to use. Spring framework provides
support for post-initialization and pre-destroy methods in spring beans.
The process of injection spring bean dependencies while initializing it, is called spring bean
wiring.
Spring framework also supports the possibility of doing autowiring. We can use
@Autowired annotation with fields.
For auto wiring annotation to work, we need to enable annotation based configuration in
spring bean. This can be done by context:annotation-config element.
5/35
Question: What are different types of Spring Bean autowiring?
Autowire byName
Autowire byType
Autowire by constructor
Autowiring by @Autowired and @Qualifier annotations
The default scope of Spring bean is singleton, so there will be only one instance per
context. So this means that Spring beans are not thread safe by default.
However we can change spring bean scope to request, prototype or session to achieve
thread-safety at the cost of performance.
Singleton Pattern
Factory Pattern
Proxy Pattern
Template Method Pattern
Front Controller
Prototype Pattern
Adapter Pattern
Data Access Object
Model View Controller
Scope prototype means that every time an instance of the Bean is called. Spring will create
a new instance and return it.
This differs from the default singleton scope, where a single object instance is instantiated
once per Spring IoC container.
SECOND: Using @Autowired annotation with bean variable of type ServletContext and
ServletConfig.
Question: BeanFactory VS
ApplicationContext?
It also extends the BeanFactory interface but the default implementation instantiates beans
eagerly when the application starts. This behavior can be overridden for individual beans.
Dependency Injection allows the developers to remove the hard coded dependencies
among components and make the application loosely coupled, extendable and
maintainable.
-Loose coupling
-Separation of Concerns
In Spring framework dependency injection can be implemented by using Spring XML based
configuration or by using annotation based configuration.
Spring supports following modes to instruct Spring container to use autowiring for
dependency injection.
No:
Default, no auto wiring
byName:
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 name of bean in xml configuration file.
byType:
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 itstype matches with exactly one of the beans
name in configuration file.
contructor:
byType mode in constructor argument.
autodetect:
Spring first tries to wire using autowire by constructor, if it does not work, Then spring tries
to autowire by byType.
8/35
Question: What Is Aspect Oriented Programming?
AOP takes out the direct dependency of cross-cutting tasks from classes that is not
possible in normal object oriented programming.
AOP provides the way to dynamically add the cross-cutting concern before, after or around
the actual logic by using simple pluggable configurations.
It makes the code easy to maintain. You can add/remove concerns without recompiling
complete code.
Aspects can be a normal class configured in spring bean configuration file or it can
be spring aspect using @Aspect annotation.
Advice: Advice is the action taken for a particular join point. In terms of programming, they
are methods that gets executed when a specific join point with matching pointcut is reached
in the application.
Join Point: A join point is a specific point in the application such as method execution,
exception handling. In Spring AOP a join points is always the execution of a method.
Advice Arguments: We can pass arguments in the advice methods. We can use args()
expression in the pointcut to be applied to any method that matches the argument pattern.
If we use this, then we need to use the same name in the advice method from where
argument type is determined.
Spring supports following modes to instruct Spring container to use autowiring for
dependency injection.
No:
Default, no auto wiring
byName:
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 name of bean in xml configuration file.
byType:
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 configuration
file.
contructor:
byType mode in constructor argument.
autodetect:
10/35
Spring first tries to wire using auto wire by constructor, if it does not work, Then spring tries
to auto wire by byType.
1. AspectJ
2. Spring AOP
3. JBoss AOP
1. Before advice: Advice that executes before a join point, you need to
use @Before annotation to enable it.
A a proxy is an object that looks like another object, but adds special functionality behind
the scene.
11/35
AOP proxy is an object created by the AOP framework in order to implement the aspect
contracts in runtime.
Spring AOP defaults to using standard JDK dynamic proxies for AOP
proxies. This enables any interface to be proxeed.
Spring AOP can also use CGLIB proxies. This is necessary to proxy
classes, rather than interfaces.CGLIB is used by default if a business object
does not implement an interface.
Weaving is the process of linking aspects with other out side application
types or objects to create an advised object.
This can be done at compile time, load time, or at runtime. Spring AOP, like
other pure Java AOP frameworks, performs weaving at runtime only. In
contrast, AspectJ framework supports both compile-time and load-time
weaving.
12/35
The Spring MVC framework provides Model-View-Controller architecture and various
components that can be used to develop flexible and loosely coupled web applications.
The MVC pattern results in separating the different aspects of the application, while
providing a loose coupling between these elements.
The Model encapsulates the application data and in general they will consist of
POJO.
The View is responsible for rendering the model data and in general it generates
HTML output that the client's browser can interpret.
The Controller is responsible for processing user requests and building an
appropriate model and passes it to the view for rendering.
1- @ExceptionHandler
By Using @ExceptionHandler at controller level. This approach has a major feature, the
@ExceptionHandler annotated method is only active for that particular controller, not
globally for the entire application.
2- @HandlerExceptionResolver
3- @ControllerAdvice
Spring MVC Interceptors allow us to intercept a client request and process it at three
places.
1. Before handling
2. After handling
3. After completion of a request. The interceptor can be used for cross-cutting concerns
and to avoid repetitive handler code like logging, changing globally used parameters in
Spring model, etc.
13/35
Question: What is a Controller in Spring MVC?
Controller - Controller acts on both model and view. It controls the data flow into model
object and updates the view whenever data changes. It keeps view and model separate.
Simply put, all the requests processed by the DispatcherServlet are directed to classes
annotated with @Controller. Each controller class maps one or more requests to methods
that process and execute the requests with provided inputs.
@Component: is used to indicate that a class is a component. These classes are used for
auto detection and configured as bean.
ViewResolver implementations are used to resolve the view pages by name. Usually they
are configured in the spring bean configuration file.
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the
/WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
Spring comes with MultipartResolver to handle file upload in web application. There are two
concrete implementations included in Spring
14/35
Question: What is ContextLoaderListener?
ContextLoaderListener is the listener class used to load root context and define spring bean
configurations that will be visible to all other contexts. It’s configured in web.xml file as
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
3- Spring bean configuration file to define beans, if using annotations then it has to be
configured here. Also we need to configure view resolver for view pages.
4- Controller class with request mappings defined to handle the client requests.
Spring provides excellent support for localization or i18n through resource bundles. Basis
steps needed to make our application localized are
Yes, this is possible by using @ResponseBody annotation. This is how we send JSON or
XML based response in restful web services.
Spring provides built-in support for uploading files through MultipartResolver interface
implementations.
Spring MVC Interceptors allow us to intercept client request and process it. We can
intercept client request at three places
– preHandle
- postHandle
- afterCompletion
It is used simultaneously with the @Autowired annotation to avoid confusion when multiple
instances of a bean type are present.
@Autowired annotation can be used with fields or methods for injecting a bean by type.
This annotation allows Spring to resolve and inject collaborating beans into your bean.
REST stands for Representational State Transfer. Which uses HTTP protocol to send
data from client to server. Like a book in the server can be delivered to the client using
JSON or XML.
REST API uses HTTP methods to perform operations. Some of the HTTP operations which
doesn’t modify the resource at the server is known as safe operations e.g. GET and HEAD.
Operations like PUT, POST, and DELETE are unsafe because they modify the resource on
the server.
Yes, REST is Scalable. It doesn’t depends upon a specific technology both at client and
server side. You can use any technology like Java, C++, Python or JavaScript to create
17/35
RESTful web services and consume them at the client side.
REST can use any HTTP methods but the most popular ones are
Yes, REST API is stateless because it is based on HTTP protocol, which is also stateless.
A Request in REST API should contain all the details required it to process.
And it should not rely on some data maintained at the server end. REST specification put a
constraint to make it stateless and developers should keep that in mind while designing
REST API.
3 return bookRepository.save(testBook);
4 }
18/35
You can similarly create other handler methods to produce JSON or XML.
There is no strict rule with respect to what status code your REST API should return after a
successful DELETE operation.
In general, if the DELETE operation is successful and the response body is empty return
204.
If the DELETE request is successful and the response body is NOT empty, return 200
The @ResponseStatus annotation is required during error handling in Spring MVC and
REST. Normally when an error or exception is thrown at server side, web server returns
"HTTP status code 500 – Internal server error". But for REST clients. User needs to send a
proper status code e.g. 404 if the resource is not found. That’s where you can use
@ResponseStatus annotation, which allows you to send custom HTTP status code along
with proper error message in case of Exception.
Normally REST is not secure but you can secure it by using Spring security.
Developers can also enable HTTP basic authentication by using HTTP Spring security
configuration file. Similarly, we can expose REST API using HTTPS to add an extra layer of
security.
We can use Spring Framework to create Restful web services that returns JSON data.
Spring provides integration with Jackson JSON API that can be used to send JSON
response in restful web service.
Following steps are needed to configure Spring MVC application to send JSON response:
-In the controller handler methods, return the Object as response using
@ResponseBodyannotation.
19/35
-You can invoke the rest service through any API, but if you want to use Spring then we can
easily do it using RestTemplate class.
It takes an opinionated view of the Spring platform so that new and existing users can
quickly get to the bits they need.
You can use it to create stand-alone Java applications that can be started using ‘java -
jar’ or more traditional WAR deployments. We also provide a command line tool that runs
‘spring scripts’.
Spring Framework
Spring Framework is based on Dependency Injection. At the core of all Spring Modules is
Dependency Injection or IOC Inversion of Control.
When DI or IOC is used properly, we can develop loosely coupled applications. And loosely
coupled applications can be easily unit tested.
20/35
Spring MVC
Spring MVC Framework provides decoupled way of developing web applications. With
simple concepts like Dispatcher Servlet, ModelAndView and View Resolver, it makes it
easy to develop web applications.
Spring Boot
The problem with Spring and Spring MVC is the amount of configuration that is needed.
Spring Boot solves this problem through a combination of Auto Configuration and Starter
Projects.
Spring Boot also provide a few non functional features to make building production ready
applications easier and much faster.
Starters are a set of convenient dependency descriptors that you can include in your
application.
You get a single entry point for all the spring and related technology that you need, without
having to hunt through sample code and copy paste loads of dependency descriptors.
For example, if you want to get started using Spring and JPA for database access, just
include the spring-boot-starter-data-jpa dependency in your project, and you are good to
go.
spring-boot-starter-web-services
spring-boot-starter-web
spring-boot-starter-test
spring-boot-starter-jdbc
spring-boot-starter-hateoas
spring-boot-starter-security
spring-boot-starter-data-jpa
spring-boot-starter-data-rest
Question: What Is The Java Version Required for Spring Boot 2 and
Spring 5?
Spring Boot 2.0 requires Java 8 or later. Java 6 and 7 are no longer supported.
21/35
Question: Why spring-boot-maven-plugin Is Needed?
It makes it easy to use data access technologies, relational and non-relational databases,
map-reduce frameworks, and cloud-based data services.
Spring Data REST can be used to expose HATEOAS RESTful resources around Spring
Data repositories.
If you are using Eclipse IDE, Eclipse maven plugin ensures that as soon as you add a
dependency or make a change to the class file, it is compiled and ready in the target folder!
And after that its just like any other Java application. When you launch the java application,
then the spring boot auto configuration magic kicks in.It launches up tomcat when it sees
that you are developing a web application.
RequestMapping: It can be used with GET, POST, PUT or any other request methods
using the method attribute on the annotation.
22/35
GetMapping: It is specific to GET method. In reality GetMapping is an improvement of
RequestMapping for better clarity.
Application development lifecycle goes through various stages and gets deployed on
different environments. And often times it is necessary to have different configurations in
each environment.
Spring and Spring Boot provide features where developers can specify
Spring Boot will pick up the application configuration based on the active profile that is set
in a specific environment.
It allows the developers to use more advanced enterprise services when necessary.
-Application: Itcontains all the jobs and code developers write using the Spring Batch
framework.
-Batch Core: It contains all the API classes that are needed to control and launch a Batch
Job
-Batch Infrastructure: It contains the readers, writers, and services used by both
application and Batch components.
In a Spring Batch application, a job is the batch process that is to be executed. It runs from
start to finish without interruption. This job is further divided into steps.
We will configure a job in Spring Batch using an XML file or a Java class. Following is the
XML configuration of a Job in Spring Batch.
Step
A step is an independent part of a job which contains the necessary information to define
and execute the job (its part).
An item reader reads data into a Spring Batch application from a particular source,
whereas an item writer writes data from the Spring Batch application to a particular
destination.
An Item processor is a class which contains the processing code which processes the
data read into the spring batch. If the application reads "n"records, then the code in the
processor will be executed on each record.
When no reader and writer are given, a tasklet acts as a processor for SpringBatch. It
processes only a single task. For example, if we are writing a job with a simple step in it
24/35
where we read data from MySQL database and process it and write it to a file (flat), then
our step uses −
<job id = "helloWorldJob">
<step id = "step1">
<tasklet>
<chunk reader = "mysqlReader" writer = "fileWriter"
processor = "CustomitemProcessor" ></chunk>
</tasklet>
</step>
</ job>
Spring Batch provides a long list of readers and writers. Using these predefined classes,
we can define beans for them. We will discuss readersand writers in greater detail in the
coming chapters.
A Job repository in Spring Batch provides Create, Retrieve, Update, and Delete (CRUD)
operations for the JobLauncher, Job, and Step implementations. We will define a job
repository in an XML file as shown below.
<job-repository id = "jobRepository"/>
In addition to id, there are some more options (optional) available. Following is the
configuration of job repository with all the options and their default values.
<job-repository id = "jobRepository"
data-source = "dataSource"
transaction-manager = "transactionManager"
isolation-level-for-create = "SERIALIZABLE"
table-prefix = "BATCH_"
max-varchar-length = "1000"/>
JobLauncher is an interface which launces the Spring Batch job with the given set of
parameters. SampleJoblauncher is the class which implements
the JobLauncher interface. Following is the configuration of the JobLauncher.
<bean id = "jobLauncher"
class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name = "jobRepository" ref = "jobRepository" />
</bean>
25/35
Question: What Is Spring Batch Tasklet?
The Tasklet which is a simple interface with just one method execute. Using this we can
perform single tasks like executing queries, deleting files.
A: Spring Batch provides a Tasklet interface, which will be called to perform a single task
only, like clean or delete or set up resources before or after any step execution.
Different Readers and Writers: Provides great support to read from text files, CSV, JMS,
JDBC, Hibernate, iBatis etc. It can write to JMS, JDBC, Hibernate, files and many more.
Easy to implement proper transaction management even when using chunk processing.
Easy to implement parallel processing. With simple configuration, different steps can be run
in parallel.
Parallel processing enables multiple batch runs jobs to run in parallel to reduce the total
elapsed batch processing time. Parallel processing is simpler as long as the same file or
database table is not shared among the processes otherwise the processes should process
partitioned data.
Another approach would be using a control table for maintaining interdependencies and to
track each shared resource in use by any process or not.
Other key issues in parallel processing include load balancing and the availability of general
system resources such as files, database buffer pools etc. Also note that the control table
itself can easily become a critical resource.
26/35
The Spring Batch Meta-Data tables are used to persist batch domain objects such as
JobInstance, JobExecution, JobParameters, and StepExecution for internally managing the
Batch Jobs.
The JobRepository is responsible for saving and storing each Java object into its correct
table
JobLauncher represents a simple interface for launching a Job with a given set of
JobParameters.
Spring Framework provides excellent integration with JDBC API and provides
JdbcTemplate utility class. Developers can use this class to avoid boiler plate code from
database logic.
27/35
Declarative transaction management is most widely used because it’s easy to use and
works in most of the cases.
We need to configure transaction manager for the DataSource in the spring bean
configuration file.
Spring DAO support is provided to work with data access technologies like JDBC,
Hibernate in a consistent and easy way.
Spring ORM module is used to integrate Spring and Hibernate frameworks. Spring ORM
provides support for using Spring declarative transaction management
Spring simplifies database access handling with the Spring JDBC Template. For example
a Job repository in Spring Batch provides Create, Retrieve, Update, and Delete (CRUD)
operations for the JobLauncher.
Spring JdbcTemplate eliminates all the above problems of JDBC API. It provides methods
to write the queries directly.
The Spring JDBC Template has many advantages compared to the standard JDBC.
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.
Spring Security is a powerful and highly customizable framework that focuses on providing
both authentication and authorization to Java applications.
Like all Spring projects, the real power of Spring Security is found in how easily it can be
extended to meet custom requirements
29/35
Question: How To Achieve Transaction Management in Spring?
Declarative transaction management is most widely used because it’s easy to configure
and works smoothly.
ROLE_USER: has no meaning unless this role is assigned to users when they are
authenticated.
PreAuthorize is used to allow method access to user if a role is assigned to him. For
example PreAuthorize("hasRole('ROLE_role1')
Application will check it by a login form. User will enter user name and password and these
inputs will be validated by the application.
Spring security provides the feature to secure the specific URL patterns. For any URL
pattern if we want to allow only HTTPS access, we have to do a small configuration in the
spring security configuration.
To manage session we need to use <session-management> tag within <http> tag in our
spring context XML.
<session-management
@Secured and @RolesAllowed both annotation provide method level security in to Spring
Beans.
@Secured is Spring Security annotation from version 2.0 onwards Spring Security.
Spring Security provides the support for JSR 250 annotation as well for method level
security.
Security context in Spring Security includes details of the principal currently using the
application.
Security context is always available to methods in the same thread of execution, even if the
security context is not explicitly passed around as an argument to those methods.
Spring Security provides support for password hashing. And a salt is used to prevent
dictionary attacks against the key in the event your encrypted data is compromised.
OAuth (Open Authorization) is a simple way to publish and interact with protected data.
32/35
It allows an end user's account information to be used by third-party services, such as
Facebook, but without exposing the user's password.
The OAuth specification describes five grants for acquiring an access token:
Spring Resources
In this section you will find a list of excellent Spring resources.
Spring 4
Spring MVC,
REST with Spring
Web Flow
Spring Security
Link: https://www.manning.com/books/spring-in-action-fourth-edition
33/35
2- Spring Microservices in Action: In this book, John Carnell will teach you how to build
micro service based applications using Java and the Spring platform. This book will also
teach you about all the technology you need to develop and deploy your micro services in
the real world scenarios. Link: https://www.manning.com/books/spring-microservices-in-
action
This book also covers It also covers Spring Batch, NoSQL, and Big Data for building and
integrating various cloud computing services and resources
Link: https://www.apress.com/in/book/9781484227893
Summary
Spring is a very poplar and widely used java EE framework. It is adopted by all the major
corporations and thus have a very good job market.
But it is not very easy to appear in a Java Spring related interviews. You have already seen
in this guide that spring framework spans across a wide range of topics. As a developer you
need to be aware of these concepts.
The aim of this guide was to give you access to all the interview questions in each area of
Spring. These interview questions range from beginners to expert level developers.
In order to beat the competition and increase your chances of success in interviews, make
sure that you go through all of these questions.
- Interview Questions
AngularJS-Interview-Questions-PDF
References
34/35
https://spring.io/
https://en.wikipedia.org/wiki/Spring_Framework
https://www.journaldev.com/2696/spring-interview-questions-and-answers
http://www.baeldung.com/spring-interview-questions
https://github.com/in28minutes/spring-interview-guide
https://stackoverflow.com/questions/1061717/what-exactly-is-spring-framework-for
http://www.javainuse.com/spring/spring-security-interview-questions
https://www.concretepage.com/interview/spring-interview/interview-questions-spring-
security
https://www.dineshonjava.com/spring-security-interview-questions-and-answers/
https://www.wisdomjobs.com/e-university/spring-security-interview-questions.html
35/35