Blog
50 Spring Core Real Interview Questions Asked in MNC
- January 21, 2026
- Posted by: InterviewExpert.org
- Category: Backend Interview Preparation Spring MVC
Basics of Spring
1. What is the Spring Framework and why is it used?
Spring Framework is a lightweight, open-source Java framework used to build enterprise-level applications.
It provides a comprehensive infrastructure for developing Java applications by handling common problems like object creation, dependency management, transaction management, and security.
Why it is used:
- Reduces boilerplate code
- Promotes loose coupling
- Makes applications easy to test, maintain, and scale
- Provides ready-to-use modules like Spring MVC, Spring Security, Spring Data, etc.
In short, Spring lets developers focus on business logic instead of infrastructure code.
2. What are the key features of the Spring Framework?
The key features of Spring are:
- Inversion of Control (IoC)
Spring manages object creation and lifecycle instead of developers doing it manually. - Dependency Injection (DI)
Dependencies are injected automatically, making code loosely coupled. - Aspect-Oriented Programming (AOP)
Helps separate cross-cutting concerns like logging, security, and transactions. - Transaction Management
Provides both programmatic and declarative transaction support. - Spring MVC
Used for building web applications following MVC architecture. - Integration Support
Easy integration with Hibernate, JPA, JDBC, JMS, Kafka, etc.
These features together make Spring powerful and flexible.
3. Explain Inversion of Control (IoC).
IoC is a principle where the control of object creation and dependency management is transferred from the programmer to the Spring container, resulting in loose coupling and better maintainability.
Without IoC (Tightly Coupled)
Here, the programmer controls object creation manually.
class Engine {
public void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
public void drive() {
engine.start();
System.out.println("Car is running");
}
}
public class Main {
public static void main(String[] args) {
Engine engine = new Engine(); // Programmer creates object
Car car = new Car(engine); // Dependency injected manually
car.drive();
}
}Problems
- Car is tightly coupled to Engine
- Difficult to replace Engine (e.g., ElectricEngine)
- Harder to test and maintain
With IoC (Using Spring – Loosely Coupled)
Now Spring controls object creation and dependency injection.
Step 1: Engine Bean
@Component
class Engine {
public void start() {
System.out.println("Engine started");
}
}Step 2: Car Bean
@Component
class Car {
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
public void drive() {
engine.start();
System.out.println("Car is running");
}
}Step 3: Main Class
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext context =
SpringApplication.run(DemoApplication.class, args);
Car car = context.getBean(Car.class);
car.drive();
}
}What Happens Internally (IoC Flow)
✔ Spring creates Engine
✔ Spring creates Car
✔ Spring injects Engine into Car
✔ Programmer only uses the object
Programmer does NOT control object creation — Spring does
4. What is Dependency Injection (DI)?
Dependency Injection (DI) is a design pattern in which an object does not create its own dependencies. Instead, the required dependencies are provided (injected) from outside by a framework like Spring.
The class depends on abstractions, not on how objects are created.
Example:
class Car {
Engine engine;
Car(Engine engine) {
this.engine = engine;
}
}Here, Engine is injected into Car.
DI is the practical implementation of IoC in Spring.
5. What are the types of dependency injection supported by Spring?
Spring supports three types of Dependency Injection:
- Constructor Injection
- Dependencies are injected through the constructor
- Most recommended (mandatory dependencies)
- Setter Injection
- Dependencies are injected using setter methods
- Useful for optional dependencies
- Field Injection
- Dependencies injected directly into fields using
@Autowired - Easy but not recommended for testing
- Dependencies injected directly into fields using
Constructor Injection is preferred in real projects.
6. What is a Spring Bean?
A Spring Bean is simply a Java object managed by the Spring container.
- Spring creates the bean
- Spring manages its lifecycle
- Spring injects its dependencies
Any object that Spring manages is called a Spring Bean.
7. How do you define a bean in Spring using XML?
In XML configuration, beans are defined using the <bean> tag.
Example:
<bean id="engine" class="com.example.Engine" />
<bean id="car" class="com.example.Car">
<property name="engine" ref="engine" />
</bean>Here:
id→ Bean nameclass→ Fully qualified class name
XML-based configuration is older and less used today, but still important for interviews.
8. How do you define a bean using annotations?
A Spring bean can be defined using annotations like @Component, @Service, @Repository, @Controller, or by using @Bean inside a @Configuration class.
1. Using @Component (Most Common Way)
@Component
public class Engine {
public void start() {
System.out.println("Engine started");
}
}Spring automatically creates an Engine bean when component scanning is enabled.
2. Using Specialized Component Annotations
These are stereotype annotations (more semantic, same behavior as @Component):
@Service
public class PaymentService {
}@Repository
public class UserRepository {
}@Controller
public class UserController {
}When to use:
@Controller→ Web layer@Service→ Business logic@Repository→ DAO / Database layer
3. Using @Configuration + @Bean
Used when you want full control over object creation (third-party classes, custom logic).
@Configuration
public class AppConfig {
@Bean
public Engine engine() {
return new Engine();
}
}Method name (engine) becomes the bean name.
How Spring Finds These Beans
@ComponentScan("com.example.demo")or automatically via:
@SpringBootApplication(Spring Boot enables component scanning by default)
9. What are stereotype annotations (@Component, @Service, @Repository)?
Stereotype annotations are Spring annotations used to define beans and indicate their role in the application layer, such as @Component for generic components, @Service for business logic, and @Repository for data access.
Functionally, @Component, @Service, and @Repository behave the same, but @Repository provides extra exception handling support.
10. Differences between @Component and @Bean.
| @Component | @Bean |
|---|---|
| Used at class level | Used at method level |
| Spring scans it automatically | Defined inside @Configuration class |
| Cannot pass complex logic easily | Can include custom logic |
| Best for application classes | Best for third-party libraries |
Example of @Bean:
@Configuration
public class AppConfig {
@Bean
public Engine engine() {
return new Engine();
}
}Use @Component for your own classes and @Bean for external or complex object creation.
Spring Container & Bean Lifecycle
1. What is the Spring IoC container?
The Spring IoC (Inversion of Control) container is the core component of the Spring Framework responsible for:
- Creating objects (beans)
- Managing their lifecycle
- Injecting dependencies
- Managing configurations
Instead of developers creating objects using new, Spring IoC container does it for us.
Types of IoC Containers:
- BeanFactory – basic container
- ApplicationContext – advanced container (most commonly used)
In real projects, ApplicationContext is used almost everywhere.
2. Difference between BeanFactory and ApplicationContext.
| Feature | BeanFactory | ApplicationContext |
|---|---|---|
| Type | Basic IoC container | Advanced IoC container |
| Bean creation | Lazy (on demand) | Eager (by default) |
| Enterprise features | ❌ No | ✅ Yes |
| AOP support | Limited | Full |
| Event handling | ❌ No | ✅ Yes |
| Internationalization (i18n) | ❌ No | ✅ Yes |
BeanFactory is lightweight and basic, while ApplicationContext is enterprise-ready and recommended. Spring Boot always uses ApplicationContext internally.
3. How does Spring perform bean lifecycle management?
Spring manages the complete lifecycle of a bean, from creation to destruction. Spring controls when a bean is created, initialized, used, and destroyed.
Bean Lifecycle Steps:
- Bean instantiation
- Dependency injection
- Aware interfaces (if implemented)
- BeanPostProcessor – before initialization
- Initialization methods
@PostConstructInitializingBean
- BeanPostProcessor – after initialization
- Bean is ready to use
- Destruction phase
@PreDestroyDisposableBean
4. What is bean scope? Explain scopes in Spring.
Bean scope defines how many instances of a bean Spring creates and how long it lives. Singleton is default and most used; prototype is used when we need new objects every time.
Bean Scopes in Spring:
Singleton (Default)
- One instance per Spring container
- Shared across the application
Prototype
- New instance every time requested
- Spring does not manage destruction
Request (Web only)
- One bean per HTTP request
Session (Web only)
- One bean per HTTP session
Application
- One bean per web application
5. What is bean post processor?
A BeanPostProcessor allows developers to intercept and modify beans before and after initialization. BeanPostProcessor is a hook provided by Spring to customize beans during lifecycle.
It has two methods:
postProcessBeforeInitializationpostProcessAfterInitialization
Why is it important?
- Used internally by Spring
- Enables features like:
@Autowired@Transactional
6. How does Spring handle circular dependencies?
Spring can handle circular dependency only with setter injection, not constructor injection. This is one reason constructor injection is preferred, because it exposes design problems early.
Circular dependency occurs when:
- Class A depends on B
- Class B depends on A
Spring Behavior:
- Setter injection → ✅ Spring can resolve
- Constructor injection → ❌ Spring fails
How Spring resolves it:
Spring uses early object references and three-level cache mechanism internally.
7. What are lazy initialized beans?
Lazy initialization means a bean is created only when it is actually required, not during container startup. Lazy beans are created only when requested, not during application startup.
Default Behavior:
- Singleton beans → Eagerly initialized
Lazy Initialization:
@Lazy
@Component
public class ReportService {
}Benefits:
- Saves memory
- Faster application startup
8. What is singleton vs prototype bean?
Singleton is shared and managed fully by Spring, prototype creates a new object every time and Spring does not destroy it.
| Feature | Singleton | Prototype |
|---|---|---|
| Instances | One per container | New instance every request |
| Default scope | ✅ Yes | ❌ No |
| Lifecycle managed by Spring | Fully | Partially |
| Memory usage | Low | High |
| Use case | Shared services | Stateful objects |
Configuration
1. What are the ways to configure Spring (XML vs JavaConfig)?
Spring provides multiple ways to configure the application, mainly to define beans and dependencies. XML was used earlier, but today JavaConfig and annotations are the recommended way.
XML Configuration (Older Approach)
Beans are defined in an XML file.
Example:
<bean id="engine" class="com.example.Engine"/>Pros:
- Clear separation between code and configuration
- Useful for legacy applications
Cons:
- Verbose
- Hard to maintain
- No compile-time checking
JavaConfig (Modern Approach)
Beans are defined using Java classes and annotations.
Example:
@Configuration
public class AppConfig {
@Bean
public Engine engine() {
return new Engine();
}
}Why JavaConfig is preferred
- Type-safe
- Easy to refactor
- Less boilerplate
- Industry standard today
2. What is @Configuration?
@Configuration is a class-level annotation that tells Spring:
“This class contains bean definitions.”
@Configuration ensures that Spring manages the beans defined inside the class properly.
Example Of @Configuration:
@Configuration
public class AppConfig {
@Bean
public Engine engine() {
return new Engine();
}
}3. What is @ComponentScan used for?
@ComponentScan tells Spring where to search for Spring-managed components. @ComponentScan eliminates the need to define each bean manually.
What it scans:
@Component@Service@Repository@Controller
Example:
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}Why it is important:
- Enables automatic bean discovery
- Avoids manual bean declaration
4. How do property files work in Spring?
Spring uses property files to externalize configuration, such as:
- Database credentials
- URLs
- Environment-specific values
Property files help separate configuration from business logic. In Spring Boot, application.properties or application.yml is used by default.
Example application.properties:
db.url=jdbc:mysql://localhost:3306/test
db.username=rootInjecting values:
@Value("${db.url}")
private String dbUrl;Advantages:
- Environment-specific flexibility
- Configuration changes without code change
5. What are profiles in Spring?
Spring Profiles allow you to define environment-specific beans. Spring Profiles help run the same application in multiple environments without code changes.
Example Environments:
devtestprod
Example:
@Profile("dev")
@Component
public class DevDataSource {
}Activate Profile:
spring.profiles.active=devWhy profiles are useful:
- Different beans for testing and production
- Different DBs for different environments
Autowiring & Qualifiers
1. What is autowiring in Spring?
Autowiring is a feature of Spring that automatically injects dependencies into a bean without explicitly defining them in configuration files.
Spring identifies which object to inject and injects it automatically.
Example
@Component
class Car {
@Autowired
private Engine engine; // Spring injects Engine automatically
}✔ No new keyword
✔ No manual wiring
✔ Cleaner and less boilerplate code
2. Types of autowiring supported by Spring.
Spring supports 4 main types of autowiring:
1. Constructor Autowiring (Recommended)
@Component
class Car {
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}✔ Best for mandatory dependencies
✔ Makes code immutable and testable
2. Setter Autowiring
@Component
class Car {
private Engine engine;
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
}✔ Useful for optional dependencies
3. Field Autowiring
@Component
class Car {
@Autowired
private Engine engine;
}✔ Short and simple
❌ Not recommended for testing (hidden dependencies)
4. Autowiring by Name / Type (XML-based – older)
<bean id="car" class="Car" autowire="byType"/>❌ Rarely used today
❌ Annotation-based configuration is preferred
3. What is @Qualifier used for?
@Qualifier is used when multiple beans of the same type exist, to tell Spring exactly which bean to inject.
❌ Problem: Ambiguity
@Component
class PetrolEngine {}
@Component
class DieselEngine {}@Autowired
private Engine engine; // ❌ Spring is confusedSolution: @Qualifier
@Autowired
@Qualifier("petrolEngine")
private Engine engine;✔ Resolves ambiguity
✔ Explicit bean selection
4. What is @Primary?
@Primary tells Spring which bean to prefer by default when multiple beans of the same type exist.
Example
@Component
@Primary
class PetrolEngine implements Engine {}@Component
class DieselEngine implements Engine {}@Autowired
private Engine engine; // PetrolEngine injected✔ No need for @Qualifier
✔ Used for default implementations
Advanced Core Concepts
1. What is Aspect-Oriented Programming (AOP) in Spring?
Aspect-Oriented Programming (AOP) is a programming paradigm used to separate cross-cutting concerns (like logging, security, transactions) from business logic.
Instead of writing the same code repeatedly in multiple classes, AOP allows you to write it once and apply it everywhere.
Example of Cross-Cutting Concerns
- Performance monitoring
- Logging
- Transaction management
- Security
Without AOP
public void saveUser() {
log.info("Method started");
// business logic
log.info("Method ended");
}With AOP
public void saveUser() {
// pure business logic
}Logging is handled separately using AOP.
2. What are advices, pointcuts, and aspects?
Advice
Advice is what action to perform (logic to run).
Examples:
- Log method call
- Start transaction
- Check security
Types of Advices:
@Before@After@AfterReturning@AfterThrowing@Around
Pointcut
Pointcut defines where the advice should be applied (which methods).
@Pointcut("execution(* com.app.service.*.*(..))")Aspect
An Aspect is a combination of advice + pointcut. It defines what to do and where to do it.
3. How does Spring implement AOP (proxy based)?
Spring AOP works using proxies.
How it works:
- Spring creates a proxy object
- Client calls the proxy
- Proxy executes advice
- Proxy calls the actual method
Client → Proxy → Advice → Target MethodProxy Types:
- CGLIB Proxy → If class-based proxy is needed
- JDK Dynamic Proxy → If interface is used
4. What is JoinPoint vs Pointcut?
| Feature | JoinPoint | Pointcut |
|---|---|---|
| Meaning | A specific execution point | A rule to select join points |
| Scope | Actual method execution | Expression |
| Example | saveUser() execution | execution(* save*(..)) |
Simple Explanation
- JoinPoint → Where something happens
- Pointcut → Which places should be selected
Pointcut selects JoinPoints.
5. Explain Spring Expression Language (SpEL).
SpEL (Spring Expression Language) is a powerful expression language used to query and manipulate objects at runtime.
Where SpEL is used:
@Value@Conditional- Security expressions
- AOP pointcuts
Example
@Value("#{2 + 3}")
private int result;@Value("#{user.name}")
private String username;@PreAuthorize("hasRole('ADMIN')")Supports:
- Collections
- Method calls
- Property access
- Logical operators
6. What is @Aspect annotation?
@Aspect is used to declare a class as an Aspect in Spring AOP.
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.app.service.*.*(..))")
public void logBefore() {
System.out.println("Method called");
}
}Tells Spring:
- Apply advices based on pointcuts
- This class contains AOP logic
7. Can Spring AOP intercept private methods?
No (only public/protected via proxies)
8. Is Spring AOP compile-time or runtime?
Runtime (Proxy-based)
Context & Dependency
1. What is ApplicationContext and its types?
ApplicationContext is the central interface of the Spring container. It is an advanced version of BeanFactory.
It is responsible for:
- Creating and managing Spring beans
- Dependency Injection
- Bean lifecycle management
- Configuration, events, and internationalization
Types of ApplicationContext
1. ClassPathXmlApplicationContext
Loads configuration from the classpath.
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");✔ Used in older XML-based applications
2. FileSystemXmlApplicationContext
Loads configuration from the file system.
ApplicationContext context =
new FileSystemXmlApplicationContext("C:/spring/beans.xml");3. AnnotationConfigApplicationContext
Used for Java-based configuration.
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);✔ Very common in modern Spring apps
4. WebApplicationContext
Used in Spring MVC / web applications.
✔ Integrated with Servlet context
✔ Managed by Spring DispatcherServlet
2. How do you load Spring context programmatically?
Spring context can be loaded programmatically using different approaches.
Using Java Configuration (Most Common)
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);Using XML Configuration
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");Using Spring Boot (Automatic)
@SpringApplication.run(DemoApplication.class, args);Spring Boot automatically loads the ApplicationContext
3. How does Spring manage dependencies at runtime?
Spring manages dependencies using Dependency Injection (DI) and Inversion of Control (IoC).
Runtime Dependency Management Flow
- Spring scans classes (
@Component,@Service, etc.) - Creates bean objects
- Resolves dependencies using:
- Type
- Name
@Qualifier/@Primary
- Injects dependencies via:
- Constructor
- Setter
- Field
- Manages bean lifecycle
Example
@Component
class Engine {
}@Component
class Car {
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}At runtime:
- Spring creates
Engine - Spring creates
Car - Spring injects
EngineintoCar
How Spring Resolves Conflicts?
| Situation | Solution |
|---|---|
| Multiple beans of same type | @Primary |
| Explicit bean selection | @Qualifier |
| Optional dependency | @Autowired(required=false) |
Exception & Error Handling
1. What exceptions are common in Spring DI?
The most common exceptions in Spring Dependency Injection are:
- NoSuchBeanDefinitionException – Spring cannot find a required bean in the context
- NoUniqueBeanDefinitionException – More than one bean of the same type exists
- UnsatisfiedDependencyException – Dependency cannot be injected due to missing or invalid configuration
- BeanCreationException – Bean fails during creation or initialization
These exceptions usually occur due to missing beans, multiple beans of the same type, incorrect component scanning, or wrong configuration.
2. How do you fix “NoSuchBeanDefinitionException”?
NoSuchBeanDefinitionException occurs when Spring cannot find a bean to inject.
To fix it:
- Ensure the class is annotated with
@Component,@Service,@Repository, or@Controller - Verify component scanning includes the package
- Check that the bean type and name match
- For XML or Java config, confirm the bean is properly declared
- Make sure the bean is not excluded by profiles or conditions
In short, Spring must know about the bean and its location.
3. How to solve “NoUniqueBeanDefinitionException”?
NoUniqueBeanDefinitionException occurs when multiple beans of the same type exist and Spring cannot decide which one to inject.
To solve it:
- Use
@Qualifierto explicitly specify the required bean - Use
@Primaryto mark one bean as the default choice - Inject by bean name instead of type
- Refactor design to reduce multiple implementations if not needed
Key point: Remove ambiguity so Spring knows exactly which bean to inject.
Bean Lifecycle Customization
1. How to use @PostConstruct and @PreDestroy?
@PostConstruct and @PreDestroy are lifecycle annotations used to execute logic after bean initialization and before bean destruction. @PostConstruct runs after DI, @PreDestroy runs before bean destruction
@PostConstruct is called after dependency injection is completed and is used for initialization logic like validation, resource setup, or loading data.
@PreDestroy is called just before the bean is removed from the container and is used for cleanup logic like closing connections or releasing resources.
They work only for Spring-managed beans and mainly for singleton scope.
Example:
@Component
class DatabaseService {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
@PreDestroy
public void destroy() {
System.out.println("Bean destroyed");
}
}Key interview points:
@PreDestroyis not guaranteed for prototype beans- Executed automatically by Spring
- No configuration required
- Preferred over XML lifecycle methods
2. What is BeanDefinition and BeanDefinitionRegistry?
BeanDefinition is a metadata object that describes a Spring bean, not the bean itself. BeanDefinition defines how a bean should be created.
It contains information like:
- Bean class
- Scope
- Constructor arguments
- Property values
- Init and destroy methods
- Lazy loading and dependencies
Spring uses BeanDefinition internally to create and manage beans at runtime.
BeanDefinitionRegistry is an interface used to register, remove, or query BeanDefinitions in the Spring container. BeanDefinitionRegistry manages and registers those definitions.
It allows dynamic bean registration before the container is fully initialized.
Example use cases:
- Custom Spring extensions
- Framework development
- Dynamic bean creation at startup
Key interview points:
- Used internally by Spring, rarely in normal applications
- BeanDefinition = bean metadata
- BeanDefinitionRegistry = storage and manager of bean metadata
Practical + Coding
1. How to inject collections (List/Set/Map) into a Spring bean?
Spring allows injecting collections when a bean depends on multiple beans of the same type.
You can inject:
List<T>orSet<T>→ All beans of typeTMap<String, T>→ Bean name as key, bean as value
Example:
@Component
class NotificationService {
private List<Notifier> notifiers;
@Autowired
public NotificationService(List<Notifier> notifiers) {
this.notifiers = notifiers;
}
}Key points:
- Commonly used in strategy and plugin patterns
- Order is preserved in
List @Qualifiercan be used to filter beans
2. How do you externalize configuration?
Externalizing configuration means keeping configuration values outside the code so they can change per environment without recompilation.
Spring supports externalize configuration using:
application.propertiesorapplication.yml- Environment variables
- Command-line arguments
Example:
app.timeout=5000@Value("${app.timeout}")
private int timeout;Or using @ConfigurationProperties for grouping related properties.
Key points:
- Central feature of Spring Boot
- Improves flexibility and environment separation
- Supports dev, test, prod profiles
3. How to register listeners in Spring context?
A Spring listener is used to listen to and react to application events, such as:
- Application startup
- Context refresh
- Context shutdown
- Custom business events
Spring follows an event-driven model internally.
Using @EventListener annotation
@EventListener is the preferred way because it is annotation-based and flexible.
@Component
public class AppEventListener {
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
System.out.println("Application context refreshed");
}
}Key Points:
- Simple and clean
- No interface implementation needed
- Supports multiple events
- Supports conditional events
Testing & Integration
1. How do you unit test Spring beans?
Unit testing Spring beans means testing a class in isolation, without starting the full Spring container unless required. For unit tests, we avoid loading Spring; for integration tests, we use Spring context.
Two common approaches
1. Pure Unit Test (Without Spring Context)
- Use JUnit + Mockito
- Fastest and most preferred for business logic
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
PaymentService paymentService;
@InjectMocks
OrderService orderService;
@Test
void testPlaceOrder() {
orderService.placeOrder();
}
}2. Spring-Based Test (With Context)
- Use when bean wiring or configuration matters
@SpringBootTest
class OrderServiceIT {
@Autowired
OrderService orderService;
}2. What is Spring TestContext Framework?
The Spring TestContext Framework provides integration testing support for Spring applications. Spring TestContext Framework bridges Spring and testing frameworks.
What it does:
- Loads Spring ApplicationContext
- Manages test lifecycle
- Supports dependency injection in tests
- Integrates with JUnit and TestNG
Core Annotations:
@SpringBootTest@ContextConfiguration@ActiveProfiles@DirtiesContext
Example:
@SpringBootTest
class UserServiceTest {
@Autowired
UserService userService;
}3. How to mock Spring beans using Mockito?
Spring allows mocking beans so that real dependencies are not called during tests. @MockBean mocks Spring-managed beans, @Mock mocks plain objects.
Best Way – @MockBean (Spring Boot)
@SpringBootTest
class OrderServiceTest {
@MockBean
PaymentGateway paymentGateway;
@Autowired
OrderService orderService;
}@MockBeanreplaces the real bean in Spring context- Used mainly in integration tests
Mockito-Only Mocking (No Spring)
@Mock
PaymentGateway gateway;
@InjectMocks
OrderService service;4. How to load only specific configuration classes in tests?
To speed up tests and avoid loading the full application context, we can load only required configuration classes. Loading minimal context improves test speed and isolation.
Using @ContextConfiguration
@ContextConfiguration(classes = TestConfig.class)
class MyServiceTest {
}Using @SpringBootTest with classes
@SpringBootTest(classes = {ServiceConfig.class})
class MyServiceTest {
}Using Test Slices (Recommended in Spring Boot)
@WebMvcTest→ Controller layer@DataJpaTest→ Repository layer@JsonTest→ JSON testing
@WebMvcTest(UserController.class)
class UserControllerTest {
}