100 Fundamental Spring Interview Questions
100 Fundamental Spring Interview Questions
html
<div>
<p align="center">
<a href="https://devinterview.io/questions/web-and-mobile-development/">
<img src="https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-
blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media&token=1b5eeecc-c9fb-
49f5-9e03-50cf2e309555" alt="web-and-mobile-development" width="100%">
</a>
</p>
#### You can also find all 100 answers here [Devinterview.io - Spring] 👉
(https://devinterview.io/questions/web-and-mobile-development/spring-interview-questions)
<br>
## 1. What is the _Spring Framework_ and what are its core features?
3. **Validation and Data Binding**: Offers powerful validation and data binding
mechanisms compatible with JavaBeans components, thereby ensuring data integrity.
4. **JDBC Abstraction and Transactions**: Provides a consistent data access layer and
unified transaction management across various data sources.
5. **ORM Support**: Simplifies Object-Relational Mapping with tools like Spring Data JPA
and Hibernate.
6. **MVC Web Framework**: Facilitates the development of flexible web applications and
RESTful services.
7. **REST Support and Content Negotiation**: Streamlines building RESTful web services
and content negotiation for better client/server communication.
8. **Security Features**: Offers a robust security framework for web applications, covering
authentication, authorization, and access-control decisions.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 1/24
05/08/2025, 00:35 tmpwauopsci.html
Language) simplifies dynamic resolution of property values in annotations or XML
configuration files.
12. **Support for Different Development Styles**: Offers support for various enterprise
application patterns like Singleton, Factory, Adapter, and so on.
13. **In-Depth Testing Support**: Spring's testing modules provide classes and
configurations for thorough unit and integration testing.
16. **Modularity**: Spring, being a modular framework, allows using only the needed
modules, minimizing runtime overhead.
<br>
To create a **simple Spring application**, you need to handle the following tasks:
```xml
<dependencies>
<!-- Core Spring Context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<!-- Web Support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 2/24
05/08/2025, 00:35 tmpwauopsci.html
<version>5.3.10</version>
</dependency>
<!-- Bootstrap Spring Web Application -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
<!-- Javax Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
```
```gradle
dependencies {
// Core Spring Context
implementation 'org.springframework:spring-context:5.3.10'
// Web Support
implementation 'org.springframework:spring-web:5.3.10'
// Bootstrap Spring Web Application
implementation 'org.springframework:spring-webmvc:5.3.10'
// Javax Servlet API
providedCompile 'javax.servlet:javax.servlet-api:4.0.1'
}
```
1. **DispatcherServlet**: Captures HTTP requests and directs them to the right controllers.
2. **ApplicationContext**: The core container for Spring's IoC and dependency injection
features.
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MySpringApp {
public static void main(String[] args) {
SpringApplication.run(MySpringApp.class, args);
}
}
```
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 3/24
05/08/2025, 00:35 tmpwauopsci.html
### WebController
Create a simple Controller that listens to GET requests. Here is the Java code:
**MainController**.java:
```java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
@RequestMapping("/")
public String home() {
return "index";
}
}
```
<br>
1. **Bean Management**: Spring manages Java objects, known as beans, by detailing their
creation, configuration and deletion through **Bean Factories**.
2. **Configurations**: Spring employs both XML and annotations for defining bean
configurations.
4. **Lifecycle Management**: Using Spring's **Bean Lifecycle**, you can manage the
instantiation, modification and disposal of beans in a systematic manner.
5. **AOP and Declarative Services**: Spring aids IoC by offering an Aspect Oriented
Programming (AOP) system and allowing declarative services via Java annotations, enabling
you to externalize cross-cutting concerns.
6. **Externally Managed Resources**: You can bring in non-bean resources like data
sources and template files under Spring IoC management, promoting resource sharing and
centralization.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 4/24
05/08/2025, 00:35 tmpwauopsci.html
```xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.10</version>
</dependency>
</dependencies>
```
```xml
<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.xsd">
<bean id="customer" class="com.example.customer.Customer">
<property name="itemName" value="Laptop" />
</bean>
<bean id="invoice" class="com.example.billing.Invoice" />
</beans>
```
In addition to XML-based configuration, you can use annotations. Add this to your XML bean
container:
```java
@Configuration
public class AppConfig {
@Bean
public Customer customer() {
Customer cust = new Customer();
cust.setItemName("Laptop");
return cust;
}
@Bean
public Invoice invoice() {
return new Invoice();
}
}
```
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 5/24
05/08/2025, 00:35 tmpwauopsci.html
```java
public class Main {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
// XML-based instantiation
Customer c1 = (Customer) context.getBean("customer");
In this example, both XML-based and annotation-based IoC and bean management are
depicted.
<br>
- **Lifecycles**: The container manages bean lifecycles, initializing and destroying them
when the application starts or shuts down.
- **Singleton**: The default. The `ApplicationContext` creates and manages a single instance
of a bean.
- **Prototype**: Each request or lookup results in a new bean instance.
There are also less commonly used scopes, such as `request`, `session`, `global session`, and
`application`.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 6/24
05/08/2025, 00:35 tmpwauopsci.html
- **Close**: Shuts down the container, releasing resources and triggering bean destruction if
necessary.
- **Refresh**: Usually used with web applications to perform a manual refresh of the
`ApplicationContext` after it's been initialized.
```java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
```java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 7/24
05/08/2025, 00:35 tmpwauopsci.html
public static class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
}
```
In this example, both the XML-based and Java-based configurations illustrate the setup of the
`ApplicationContext`.
### Benefits
- **Easy to Manage and Test**: Dependencies can be swapped for testing and changed at
runtime.
- **Decoupling**: Promotes separation of concerns and reduces inter-class coupling.
- **Increased Reusability**: Makes components more reusable across systems.
Conventional approach:
- When a class $A$ needs an instance of class $B$, $A$ is responsible for creating $B$ (e.g.,
using `new`) and introducing a hard dependency, hindering flexibility and testability.
**Pros**:
- The object is always in a valid state when returned.
- It's clearer which dependencies are needed.
**Cons**:
- Constructors can grow in size.
- May not be suitable when there are optional or too many dependencies.
2. **Setter Method Injection**: The \textit{Injector} uses setter methods to inject the
dependencies after the object is created.
**Pros**:
- No need to extend classes to pass dependencies.
- Doesn't inject dependencies that are not needed.
**Cons**:
- The object can be in an inconsistent state until all dependencies are set.
3. **Field Injection**: Dependencies are provided directly into the fields or properties of the
class.
**Pros**:
- Often requires less boilerplate.
- Can be the simplest form of DI setup.
**Cons**:
- The class's dependencies are not immediately visible from its constructor or methods.
- Difficult to ensure that dependencies are not `null`.
- Breaks the encapsulation principle.
4. **Method Injection (Less Common)**: Dependencies are injected through methods that
are called after object construction. While this fulfills the Dependency Injection criteria, it's
less frequently seen in the Spring context.
**Pros**:
- Allows for flexibility in when a dependency is needed.
**Cons**:
- Increases complexity as clients need to manage when to call these methods.
- Breaks encapsulation.
```java
/* Constructor Injection */
public class ReportService {
private final DatabaseRepository databaseRepository;
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 9/24
05/08/2025, 00:35 tmpwauopsci.html
}
}
**Spring** allows you to specify different **bean scopes**. Each scope serves a unique
lifecycle and context interaction.
1. **Singleton** (default): A single bean instance is managed per container. This scope is
suitable for stateless beans.
2. **Prototype**: A new instance per bean reference or look-up. This scope is beneficial for
stateful beans.
5. **Global Session**: Functions similarly to the **Session** scope, but is meant for
**portlet-based environments**.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 10/24
05/08/2025, 00:35 tmpwauopsci.html
7. **WebSocket**: Introduced in Spring 5.0, this scope is associated with the lifecycle of a
WebSocket connection. The bean will remain in scope as long as the WebSocket connection is
active. It's often used for managing attributes and operations related to the WebSocket session.
<br>
In Spring, a **bean** represents an object that's managed by the Spring IoC (Inversion of
Control) Container. Developers can configure beans using annotations, XML, or Java code.
```java
import org.springframework.stereotype.Component;
@Component
public class MyService {
// Bean logic here
}
```
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 11/24
05/08/2025, 00:35 tmpwauopsci.html
Here is the XML code:
```xml
<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.xsd">
Modern Spring applications often favor Java-based configuration using `@Configuration` and
`@Bean` annotations.
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
```
<br>
**Spring Core container** serves as the foundation for the Spring Framework, providing the
**inversion of control** (IoC) and **dependency injection** (DI) mechanisms.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 12/24
05/08/2025, 00:35 tmpwauopsci.html
- **BeanFactory**: The basic IoC container, which is primarily responsible for the
instantiation and management of beans. It provides basic features of DI and doesn't support
advanced features such as AOP.
- **ApplicationContext**: This is an advanced version of the BeanFactory. It incorporates all
the functionalities of the BeanFactory and adds context-specific behavior. It's the prevalent
choice for most scenarios and stands as the client's gateway into the Spring world. It provides
additional features such as AOP, message source, and event publication.
- **Explicit Registration**: Developers can define beans either in XML configuration files or
using annotations (like `@Component`, `@Service`, `@Repository`, `@Controller`) and Java-
based configurations.
- **Implicit Registration**: Some classes in Spring are automatically detected and
registered if the necessary annotations are present.
The container manages a bean's lifecycle and its visibility from other beans based on the bean
scope.
- **Singleton**: The default scope, where a single instance is managed per container.
- **Prototype**: Defines that a new instance should be created and managed each time it's
requested.
- **Inversion of Control (IoC)**: Refers to the pattern in which objects delegate the
responsibility of their creation and management to another party (the IoC container).
- **Dependency Injection (DI)**: Describes the process of providing the dependencies
(collaborating objects) to a component from an external source.
- **Loose Coupling**: Components are less dependent on each other, which enhances system
flexibility and maintainability.
- **Simplified Unit Testing**: Easier with singletons and DI, as you can mock or provide
test-specific dependencies.
- **Centralized Configuration**: Configuration details are consolidated, simplifying
management and reducing the likelihood of redundancy or inconsistencies.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 13/24
05/08/2025, 00:35 tmpwauopsci.html
**Spring configuration files** provide a way to configure Spring applications. These files,
often written in XML, contain **bean definitions** and other configuration elements.
- **Bean Definitions**: XML files define beans using `bean` elements, or annotation-based
configurations can be used.
- **Module Configurations**: These files specify Spring modules to use, such as `context`,
`mvc`, or `aop`.
- **External Configurations**: XML files can import other Spring configurations, often used
in larger projects.
```xml
<import resource="xyz.xml" />
```
- **Separation of Concerns**: Divide configuration files based on the functional parts they
control, such as one for data access and another for web components.
- **Consistency and Standardization**: Establish best practices across the team. This
ensures that configurations are maintained uniformly.
- **Minimize Global Settings**: While Spring offers a global application context, it’s often
better to have smaller, more focused contexts for specific application layers or modules.
```xml
<beans>
<bean id="customerService" class="com.example.CustomerService" />
<bean id="customerDAO" class="com.example.CustomerDAO">
<property name="cassandraTemplate" ref="cassandraTemplate" />
</bean>
<bean id="cassandraTemplate"
class="org.springframework.data.cassandra.CassandraTemplate">
<constructor-arg name="session" ref="cassandraSession" />
</bean>
<bean id="cassandraSession" class="com.datastax.driver.core.Session" factory-
method="connect" />
</beans>
```
<br>
The **ApplicationContext** serves as the core of the Spring IoC container and is
fundamental to the setup of any Spring-based application.
```java
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
```
```java
ApplicationContext context = new
FileSystemXmlApplicationContext("path/to/applicationContext.xml");
```
```java
ApplicationContext context = new XmlWebApplicationContext();
```
```java
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
```
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 15/24
05/08/2025, 00:35 tmpwauopsci.html
```java
GenericApplicationContext context = new GenericApplicationContext();
context.refresh(); // Call refresh manually
```
```java
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.load("path/to/applicationContext.xml");
context.refresh();
```
```java
ApplicationContext context = new SilentModeApplicationContext();
```
- **XML vs. Java-based Config**: XML is well-suited for larger, stable applications, while
**Java-based** configurations offer better refactoring tools and compile-time safety.
For example, you might have logging code scattered throughout your application, triggered at
various points. With AOP, you can consolidate this logic separately, marking points in the code
(e.g., method calls) where logging should occur.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 16/24
05/08/2025, 00:35 tmpwauopsci.html
- **Aspect**: A module of classes containing related advice and join point definitions.
- **Join Point**: A point in the execution of the application (such as a method call or
exception being thrown) that can be targeted by advice.
- **Advice**: The action that should be taken at a particular join point (e.g., the code to
execute before a method is called).
The three weaving mechanisms can be further categorized into four strategies:
- **Singleton weaving**: The aspect is a singleton and is woven into the client at most once.
- **Per-instance weaving**: The aspect is woven into each object before it is returned.
- **Single-time weaving**: The aspect is woven into the client the first time it is
instantiated.
- **Combination-of-above weaving**: A combination of the above strategies is used to
achieve weaving.
- **Simplicity**: The application's core components can remain clean and focused on their
main tasks.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 17/24
05/08/2025, 00:35 tmpwauopsci.html
#### Aspect
An **aspect** is a module encapsulating concerns such as logging or security. These typically
cross-cut multiple application modules.
#### Advice
The action taken by an aspect at a particular join point. Different types of advice include
*before*, *after*, *around*, *after-returning*, and *after-throwing*.
#### Pointcut
A rule in AOP that defines the join points where advice should be applied. For example, you
might specify that a particular advice applies to methods whose name begins with "get".
#### Introduction
The introduction allows adding new methods or attributes to a class.
- **Proxy**: Spring AOP uses JDK dynamic proxies or CGLIB to generate a proxy for the
target object. The proxy provides an opportunity to intercept the method invocations to apply
the aspects. Spring applies the most appropriate proxy type, based on the context and the
configuration.
- **Weaving**: This is the process of linking the aspects with the application objects. Weaving
can be achieved at different points in the application life cycle, providing flexibility. Spring
supports three weaving mechanisms:
- **Compile-time weaving**: Aspects are incorporated into the application code during
compilation.
- **Load-time weaving**: Weaving takes place at the class loading time using a class loader
to load the modified classes.
- **Run-time weaving**: Weaving happens during runtime, either programmatically or
using an agent.
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 18/24
05/08/2025, 00:35 tmpwauopsci.html
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect
@Configuration
public class SecurityAspect {
@Bean
public SecurityManager securityManager() {
return new SecurityManager();
}
@Around("execution(* com.example.app.service.*.*(..))")
public Object applySecurity(ProceedingJoinPoint joinPoint) throws Throwable {
SecurityManager securityManager = securityManager();
if (securityManager.isAuthenticated()) {
return joinPoint.proceed();
} else {
throw new SecurityException("User is not authenticated.");
}
}
}
```
<br>
A **Pointcut** in Spring AOP defines the join points matched for advice and determines the
regions in an application where cross-cutting concerns are applied.
Certain attributes are fundamental to Pointcuts. For example, the **scope** of the
application and the type of join points, for instance, the Start of the Method of execution or
even well within its body.
To apply AOP in Spring, mark the points in your application where cross-cutting is required.
From there, define methods using annotations such as `@Before`, `@After`, or `@Around` to
apply the advice.
```java
@Aspect
@Component
public class LoggingAspect {
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 19/24
05/08/2025, 00:35 tmpwauopsci.html
// Define Pointcuts
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceLayerExecution() {}
@Before("serviceLayerMethodsWithLongArg()")
public void logServiceMethodWithLongArg(JoinPoint joinPoint) {
System.out.println("Before method execution: " + joinPoint.getSignature().getName());
}
}
```
In this example:
- `logServiceMethodWithLongArg()`: This is the advice that's applied before the defined join
points.
**Join Points**: The specific times during program execution when **Advices** execute.
- **After**: Executes the advice after the join point; applicable for both successful and failing
conditions.
- **Around**: Provides control over when and if the method proceeds to its natural
execution. This enables advice to be run before and after the method execution.
- **AfterReturning**: Only runs when the join point method is successfully completed.
- **AfterThrowing**: Only applies when the join point method throws an exception.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 20/24
05/08/2025, 00:35 tmpwauopsci.html
A **Join Point** in **Spring AOP** represents a specific point during the execution of a
program, which could be targeted for additional functionality, such as before, after, or around
method calls.
When a join point is intercepted by a Spring AOP advice, the advice can perform certain
actions. The availability of join points differs across diverse AOP methodologies. For example,
AspectJ provides more extensive join points than proxy-based AOP in Spring.
```java
public class SampleClass {
private int sampleField;
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 21/24
05/08/2025, 00:35 tmpwauopsci.html
public int getSampleField() {
// Join Point: Field Access
System.out.println("Getting Sample Field: " + sampleField);
return sampleField;
}
static {
// Join Point: Class Initialization
System.out.println("SampleClass Initialized.");
}
public SampleClass() {
// Join Point: Instance Construction
System.out.println("SampleClass Instance Created.");
}
}
```
<br>
## 15. What is the difference between a _Concern_ and a _Cross-cutting Concern_ in _Spring
AOP_?
**Cross-cutting concerns** are aspects of software development that affect the entire
application, yet are largely kept separate from the core business logic. This separation
improves the modularity, maintainability, and reusability of the codebase.
While a "concern" is a more general term, referring to anything that requires the application's
attention, a "cross-cutting concern" specifically relates to the aspects that cut across different
modules or layers of a software system.
The AOP approach of managing such concerns employs join points, pointcuts, and advice, and
is separate from method-specific or local object concerns.
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 22/24
05/08/2025, 00:35 tmpwauopsci.html
**Bean Class:**
```java
public class MyBook {
private String bookName;
**LogAspect:**
```java
@Aspect
public class LogAspect {
@Before("execution(* MyBook.getBookName())")
public void logMethodName(JoinPoint joinPoint) {
System.out.println("Method invoked: " + joinPoint.getSignature());
}
}
```
**AppConfig:**
```java
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
@Bean
public MyBook myBook() {
return new MyBook();
}
@Bean
public LogAspect logAspect() {
return new LogAspect();
}
}
```
<br>
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 23/24
05/08/2025, 00:35 tmpwauopsci.html
<br>
<a href="https://devinterview.io/questions/web-and-mobile-development/">
<img src="https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-
blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media&token=1b5eeecc-c9fb-
49f5-9e03-50cf2e309555" alt="web-and-mobile-development" width="100%">
</a>
</p>
file:///private/var/folders/v2/zfmtbf7d5dzcydgksccfr6bw0000gn/T/tmpwauopsci.html 24/24