Practice commonly asked
Spring Framework interview questions with clear answers and explanations.
30
Interview Questions
Questions & Answers
Spring Framework Interview Questions
30 Questions
Q 1
How does Spring manage declarative asynchronous method execution with @Async and @EnableAsync?
Medium
Answer
Annotating a method with @Async instructs Spring AOP to execute the method in a separate thread from a TaskExecutor thread pool. The method can return void or CompletableFuture<T>. @EnableAsync must be placed on a @Configuration class to activate proxy interception.
Explanation
Always configure a dedicated ThreadPoolTaskExecutor; otherwise Spring defaults to SimpleAsyncTaskExecutor which creates a new thread per invocation.
Code Example
Java
@Configuration
@EnableAsync
public class AsyncConfig {}
@Service
public class EmailService {
@Async
public CompletableFuture<Boolean> sendEmail(String to, String msg) {
// Executes asynchronously in worker thread pool
return CompletableFuture.completedFuture(true);
}
}
Reference:
Spring Framework
Q 2
What is the difference between Spring Security WebSecurityConfigurerAdapter (legacy) vs SecurityFilterChain (modern Spring Security)?
Hard
Answer
WebSecurityConfigurerAdapter used inheritance-based configuration requiring classes to override configure(HttpSecurity). In modern Spring Security (Spring 5.7+ / 6+), it was replaced by component-based configuration where security rules are defined by registering a @Bean of type SecurityFilterChain using lambda DSL.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults())
.build();
}
}
Reference:
Spring Framework
Q 3
What is the role of ContextLoaderListener vs DispatcherServlet in legacy Spring MVC web.xml applications?
Hard
Answer
ContextLoaderListener creates the Root WebApplicationContext containing shared cross-cutting service, repository, and security beans. DispatcherServlet creates a Child WebApplicationContext containing MVC controllers, view resolvers, and handler mappings, inheriting all beans from the root context.
Explanation
Child contexts can see root beans, but the root context cannot see child controller beans.
What is the difference between @Configuration and @Component in Spring bean definition?
Hard
Answer
In @Configuration classes, @Bean methods are proxied via CGLIB by default (proxyBeanMethods = true) so that calling @Bean methods internally returns the cached singleton bean instance without creating new objects. In @Component classes (Lite Mode), calling @Bean methods directly executes regular Java method calls, creating multiple duplicate instances.
Explanation
Full configuration mode (@Configuration) guarantees singleton semantics across inter-bean method references.
Code Example
Java
@Configuration // Full mode (CGLIB proxied)
public class AppConfig {
@Bean public Engine engine() { return new Engine(); }
@Bean public Car car() {
return new Car(engine()); // Calls CGLIB proxy, returning singleton Engine
}
}
Reference:
Spring Framework
Q 5
What is the difference between Caching (@Cacheable, @CachePut, @CacheEvict) in Spring Framework?
Medium
Answer
@Cacheable stores method results in cache and skips method execution on subsequent calls with matching parameters. @CachePut always executes the method and updates the cache with the new result. @CacheEvict removes stale entries from the cache.
Explanation
Spring provides declarative caching abstraction over various cache providers (Ehcache, Caffeine, Redis) via CacheManager.
Code Example
Java
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product getProduct(Long id) { return productDao.findById(id); }
@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) { return productDao.save(product); }
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) { productDao.delete(id); }
}
Reference:
Spring Framework
Q 6
What is the difference between @Primary and @Qualifier in Spring Dependency Injection?
Easy
Answer
@Primary designates a default candidate bean to be injected when multiple beans of the same type exist. @Qualifier specifies the exact bean name at the injection target point, overriding @Primary if both are present.
Explanation
If multiple beans exist without @Primary or @Qualifier, Spring throws NoUniqueBeanDefinitionException.
Code Example
Java
@Component @Primary
public class DefaultEmailService implements MessageService {}
@Component("sms")
public class SmsService implements MessageService {}
// Injection:
@Autowired
@Qualifier("sms") // Overrides @Primary and injects SmsService
private MessageService service;
Reference:
Spring Framework
Q 7
What is the difference between @Bean and @Component in Spring?
Easy
Answer
@Component is a class-level annotation detected automatically via component scanning (@ComponentScan). @Bean is a method-level annotation placed inside @Configuration classes, typically used to instantiate, configure, and register third-party library classes that you cannot modify with @Component.
Explanation
Use @Component for your own domain/service classes; use @Bean methods to configure external classes (like Jackson ObjectMapper or DataSource).
Code Example
Java
@Configuration
public class ThirdPartyConfig {
@Bean // Creates bean from external library class
public ObjectMapper objectMapper() {
return new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
}
Reference:
Spring Framework
Q 8
What is the difference between @PathVariable, @RequestParam, @RequestBody, and @ModelAttribute in Spring MVC?
Easy
Answer
@PathVariable extracts values from URI template paths (/users/{id}). @RequestParam extracts query parameters or form fields (?page=1). @RequestBody deserializes HTTP body JSON/XML into a Java object using HttpMessageConverters. @ModelAttribute binds form request parameters to a POJO model object.
Explanation
@RequestBody is standard for REST JSON APIs; @ModelAttribute is standard for traditional server-rendered HTML form submissions.
Code Example
Java
@RestController
public class UserController {
@PostMapping("/users/{deptId}")
public User createUser(
@PathVariable Long deptId,
@RequestParam(defaultValue = "true") boolean active,
@Valid @RequestBody UserDTO dto
) { return userService.create(deptId, active, dto); }
}
Reference:
Spring Framework
Q 9
What is an HandlerInterceptor in Spring MVC and how does it differ from a Servlet Filter?
Hard
Answer
A Servlet Filter is part of the Servlet container and intercepts raw requests before reaching DispatcherServlet. An HandlerInterceptor is part of Spring MVC, executes inside DispatcherServlet, and has access to the Spring ApplicationContext and target handler method execution (preHandle, postHandle, afterCompletion).
Explanation
Use Servlet Filters for low-level protocol/security tasks (CORS, compression). Use HandlerInterceptors for MVC-specific tasks (logging controllers, auth token parsing).
Code Example
Java
public class AuditInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
System.out.println("Intercepted request: " + req.getRequestURI());
return true; // continue pipeline
}
}
Reference:
Spring Framework
Q 10
What is the difference between @ControllerAdvice and @ExceptionHandler in Spring MVC?
Medium
Answer
@ExceptionHandler defines a method that handles specific exceptions thrown by controller request handlers. Placed inside a single @Controller, it handles exceptions for that controller only. Placed inside a @ControllerAdvice (or @RestControllerAdvice), it acts as a global exception interceptor across all controllers.
Explanation
@RestControllerAdvice combines @ControllerAdvice and @ResponseBody to return clean JSON error payloads from global exception methods.
Code Example
Java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(ResourceNotFoundException ex) {
return new ErrorResponse(404, ex.getMessage());
}
}
Reference:
Spring Framework
Q 11
What is the Spring Event publication system (ApplicationEvent & @EventListener)?
Medium
Answer
Spring provides an in-memory Observer pattern mechanism. An event is published via ApplicationEventPublisher.publishEvent(). Interested beans receive the event using @EventListener. By default, event execution is synchronous; annotating listener with @Async executes it concurrently.
Explanation
@TransactionalEventListener can bind event execution to specific transaction lifecycle phases (e.g. AFTER_COMMIT).
Code Example
Java
// Event definition
public record OrderPlacedEvent(Long orderId) {}
@Service
public class OrderService {
@Autowired private ApplicationEventPublisher publisher;
public void createOrder() {
publisher.publishEvent(new OrderPlacedEvent(101L));
}
}
@Component
public class NotificationListener {
@EventListener
public void onOrderPlaced(OrderPlacedEvent event) {
System.out.println("Send email for order: " + event.orderId());
}
}
Reference:
Spring Framework
Q 12
What is the role of JdbcTemplate and how does Spring solve JDBC boilerplate and exception handling?
Medium
Answer
JdbcTemplate executes SQL queries, iterates ResultSets, and automatically manages Connection opening/closing and Statement cleanups. It translates database-specific checked SQLExceptions into Spring's hierarchy of unchecked DataAccessExceptions.
Explanation
RowMapper<T> is used with JdbcTemplate to map ResultSet rows cleanly to domain POJO models.
Code Example
Java
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public User findById(Long id) {
return jdbcTemplate.queryForObject(
"SELECT id, username FROM users WHERE id = ?",
(rs, rowNum) -> new User(rs.getLong("id"), rs.getString("username")),
id
);
}
}
Reference:
Spring Framework
Q 13
What is the Spring Expression Language (SpEL) and how is it used?
Medium
Answer
SpEL is a powerful expression language supporting querying and manipulating an object graph at runtime. It evaluates expressions denoted by #{...} in XML/Java annotations, supporting method invocation, property access, relational operators, and bean references.
Explanation
Do not confuse SpEL #{expression} (dynamic evaluation) with property placeholder ${property.name} (static configuration lookup).
Code Example
Java
@Component
public class TaxService {
@Value("#{systemProperties['user.country']}")
private String defaultCountry;
@Value("#{orderService.calculateDiscount(100)}")
private double calculatedDiscount;
}
Reference:
Spring Framework
Q 14
What is the difference between BeanPostProcessor and BeanFactoryPostProcessor in Spring?
Hard
Answer
BeanFactoryPostProcessor operates on BeanDefinition configuration metadata BEFORE actual bean instances are created (e.g., PropertySourcesPlaceholderConfigurer resolving ${properties}). BeanPostProcessor operates on bean instances AFTER they are instantiated and properties are populated (wrapping beans into AOP proxies).
Explanation
BeanFactoryPostProcessor modifies the blueprints; BeanPostProcessor intercepts and modifies the created objects.
Code Example
Java
@Component
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) {
// Inspect or modify bean definition metadata
BeanDefinition def = factory.getBeanDefinition("myService");
def.setScope("prototype");
}
}
Reference:
Spring Framework
Q 15
What is the difference between @Component, @Service, @Repository, and @Controller in Spring?
Easy
Answer
@Component is the generic stereotype annotation for any Spring-managed component. @Service indicates business domain service logic. @Repository indicates data access layer components and automatically enables PersistenceExceptionTranslationPostProcessor (translating SQL/DB exceptions to Spring DataAccessExceptions). @Controller indicates web/MVC presentation handlers.
Explanation
@Service, @Repository, and @Controller are specialized meta-annotations containing @Component.
Code Example
Java
@Repository // Automatically translates vendor SQLExceptions to Spring DataAccessException
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
}
Reference:
Spring Framework
Q 16
How does Spring MVC DispatcherServlet process an incoming HTTP request?
Hard
Answer
The flow is: 1. Request hits DispatcherServlet (Front Controller), 2. DispatcherServlet consults HandlerMapping to find Controller, 3. HandlerAdapter invokes the Controller method, 4. Controller processes request and returns ModelAndView (or @ResponseBody response), 5. ViewResolver resolves logical view name to actual View (JSP/Thymeleaf), 6. View renders model data into HTTP response.
Explanation
For REST APIs (@RestController / @ResponseBody), HttpMessageConverter (e.g. Jackson) writes the response body directly to output stream, bypassing ViewResolvers.
Code Example
Java
@Controller
public class HomeController {
@GetMapping("/welcome")
public String home(Model model) {
model.addAttribute("message", "Welcome to Spring MVC");
return "homeView"; // ViewResolver maps to /WEB-INF/views/homeView.jsp
}
}
Reference:
Spring Framework
Q 17
What are Transaction Isolation Levels in Spring and what concurrency phenomena do they prevent?
What is declarative Transaction Management in Spring (@Transactional) and how does Transaction Propagation work?
Hard
Answer
@Transactional manages database transactions declaratively using AOP proxies and PlatformTransactionManager. Propagation defines how transactions boundaries interact: REQUIRED (joins existing or creates new), REQUIRES_NEW (suspends existing and starts independent transaction), MANDATORY (requires existing or throws exception), SUPPORTS, NEVER, NOT_SUPPORTED, NESTED.
Explanation
By default, @Transactional rolls back ONLY on unchecked exceptions (RuntimeException and Error). Checked exceptions must be declared with rollbackFor = Exception.class.
Code Example
Java
@Service
public class AccountService {
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void processAuditLog(String action) {
// Executes in its own isolated transaction independently
auditDao.save(action);
}
}
Reference:
Spring Framework
Q 19
Why does calling a @Transactional or AOP method internally within the same class (Self-Invocation) fail to trigger the proxy?
Hard
Answer
Spring AOP uses proxy wrappers around beans. When calling a method from outside, the call hits the proxy wrapper (interceptor). When a method calls another method inside the same class via 'this.methodB()', the call bypasses the proxy and executes on the target instance directly, skipping transactions/aspects.
Explanation
To fix self-invocation: 1. Move the transactional method to a separate helper bean, or 2. Self-inject the bean via ApplicationContext or @Autowired proxy reference.
Code Example
Java
@Service
public class OrderService {
@Autowired
private OrderService self; // Self-injected proxy reference
public void placeOrder() {
// this.saveInternal(); // BYPASSES TRANSACTION!
self.saveInternal(); // Correct: Hits the proxy interceptor
}
@Transactional
public void saveInternal() { /* DB operations */ }
}
Reference:
Spring Framework
Q 20
What is the difference between JDK Dynamic Proxies and CGLIB Proxies in Spring AOP?
Hard
Answer
JDK Dynamic Proxies generate proxies dynamically at runtime implementing target Java interfaces using java.lang.reflect.Proxy. CGLIB generates a dynamic subclass of the target concrete class using bytecode manipulation. In Spring Framework, JDK proxies are default for interface-based beans, while CGLIB is used for class-based beans.
Explanation
CGLIB cannot proxy 'final' classes or 'final' methods because it relies on class extension and method overriding.
Code Example
Java
// Enable explicit CGLIB class-based proxying:
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AopConfig {}
Reference:
Spring Framework
Q 21
What is Spring AOP and what are Aspect, JoinPoint, Pointcut, and Advice?
Hard
Answer
Spring AOP provides aspect-oriented programming for cross-cutting concerns (logging, security, transactions). Aspect is the modular class; JoinPoint is the execution point in program flow (method execution in Spring); Pointcut is the expression predicate matching join points; Advice is the action executed (Before, After, Around, AfterReturning, AfterThrowing).
Explanation
@Around advice is the most powerful advice type as it wraps method execution using ProceedingJoinPoint.proceed().
Code Example
Java
@Aspect
@Component
public class LoggingAspect {
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() {}
@Around("serviceMethods()")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
System.out.println(joinPoint.getSignature() + " took " + (System.currentTimeMillis() - start) + "ms");
return proceed;
}
}
Reference:
Spring Framework
Q 22
How does Spring detect and handle Circular Dependencies?
Hard
Answer
Spring uses a 3-level cache (singletonObjects, earlySingletonObjects, singletonFactories) to resolve circular dependencies for singleton setter/field injection by exposing early uninitialized object references. Circular dependencies in constructor injection fail immediately with BeanCurrentlyInCreationException.
Explanation
Constructor circular dependencies can be mitigated using @Lazy on one constructor parameter, but refactoring code to extract shared logic is best practice.
Code Example
Java
@Service
public class ServiceA {
private final ServiceB serviceB;
// @Lazy breaks circular constructor injection deadlock:
public ServiceA(@Lazy ServiceB serviceB) {
this.serviceB = serviceB;
}
}
Reference:
Spring Framework
Q 23
Why is Constructor Injection preferred over Field Injection (@Autowired on private fields)?
Medium
Answer
Constructor injection allows fields to be declared 'final' for immutability, prevents partial/null object instantiation, enables effortless unit testing without reflection or Spring test runners, and detects circular dependencies immediately at startup.
Explanation
Field injection hides dependencies, breaks immutability, and tightly couples domain classes to reflection-based injection containers.
Code Example
Java
@Service
public class CustomerService {
private final CustomerRepository repository; // Immutable & final
// Injected safely through constructor:
public CustomerService(CustomerRepository repository) {
this.repository = Objects.requireNonNull(repository);
}
}
Reference:
Spring Framework
Q 24
What is the difference between @Autowired, @Resource, and @Inject in Spring?
Medium
Answer
@Autowired is a Spring-native annotation that injects by Type by default (can be paired with @Qualifier for name matching). @Resource (JSR-250) injects by Name by default, falling back to Type. @Inject (JSR-330) is the standard Java DI annotation that injects by Type (paired with @Named).
Explanation
@Autowired is Spring-specific; @Resource and @Inject are standard Java specifications requiring jakarta.annotation or jakarta.inject dependencies.
Code Example
Java
@Service
public class NotificationService {
@Autowired
@Qualifier("smsSender") // Matches specific bean name
private MessageSender messageSender;
@Resource(name = "emailSender") // JSR-250 injection by name
private MessageSender emailSender;
}
Reference:
Spring Framework
Q 25
How do you solve injecting a Prototype Bean into a Singleton Bean in Spring?
Hard
Answer
Standard dependency injection wires prototype beans only once when the singleton initializes. Solutions: 1. @Lookup method injection (Spring overrides method via CGLIB), 2. ObjectFactory<T> or ObjectProvider<T>, 3. javax.inject.Provider<T>, or 4. Injecting ApplicationContext directly (violates IoC).
Explanation
@Lookup or ObjectProvider<T> are the cleanest idiomatic Spring solutions.
Code Example
Java
@Service
public class SingletonOrderService {
@Autowired
private ObjectProvider<PrototypeCart> cartProvider;
public void processNewOrder() {
PrototypeCart cart = cartProvider.getObject(); // Fresh prototype instance every time!
cart.checkout();
}
}
Reference:
Spring Framework
Q 26
What are the standard Bean Scopes in Spring Framework?
Easy
Answer
Standard scopes: singleton (default, single instance per Spring Container) and prototype (new instance on every injection/getBean()). Web-aware scopes: request (one per HTTP request), session (one per HTTP session), and application (one per ServletContext).
Explanation
Injecting a prototype bean into a singleton bean results in the prototype bean being instantiated only once during singleton initialization unless lookup methods are used.
Code Example
Java
@Component
@Scope("prototype")
public class TaskToken {
private final UUID id = UUID.randomUUID();
}
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class AppService {}
Reference:
Spring Framework
Q 27
What is the complete lifecycle of a Spring Bean?
Hard
Answer
The lifecycle order is: 1. Instantiation (constructor), 2. Populate Properties (DI), 3. Aware interfaces (BeanNameAware, BeanFactoryAware), 4. BeanPostProcessor.postProcessBeforeInitialization(), 5. Initializing callbacks (@PostConstruct, InitializingBean.afterPropertiesSet, initMethod), 6. BeanPostProcessor.postProcessAfterInitialization() (AOP Proxy creation), 7. Ready for use, 8. Destruction callbacks (@PreDestroy, DisposableBean.destroy, destroyMethod).
Explanation
BeanPostProcessors are crucial because they wrap beans in dynamic proxies for AOP, transaction handling, and security.
Code Example
Java
@Component
public class DatabaseConnector implements InitializingBean, DisposableBean {
@PostConstruct
public void init() { System.out.println("1. PostConstruct"); }
@Override
public void afterPropertiesSet() { System.out.println("2. afterPropertiesSet"); }
@PreDestroy
public void cleanup() { System.out.println("3. PreDestroy"); }
@Override
public void destroy() { System.out.println("4. destroy"); }
}
Reference:
Spring Framework
Q 28
What is the difference between BeanFactory and ApplicationContext in Spring?
Medium
Answer
BeanFactory is the basic IoC container providing lazy bean loading (instantiated on getBean()). ApplicationContext is an enterprise-grade container extending BeanFactory with eager singleton pre-instantiation, message resource i18n, event publication, and AOP integration.
Explanation
ApplicationContext is preferred for almost all standard enterprise Spring applications.
Code Example
Java
// BeanFactory: Basic & Lazy loading
// DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// ApplicationContext: Advanced & Eager pre-instantiation
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
UserService service = ctx.getBean(UserService.class);
Reference:
Spring Framework
Q 29
What is Inversion of Control (IoC) and Dependency Injection (DI) in Spring?
Easy
Answer
Inversion of Control (IoC) is a design principle where object creation, lifecycle management, and control flow are inverted from the application to a framework container. Dependency Injection (DI) is the specific design pattern used by Spring IoC Container to inject dependent objects into a bean at creation.
Explanation
Instead of classes instantiating dependencies with 'new', the Spring ApplicationContext wires dependencies automatically based on metadata.
Code Example
Java
@Service
public class OrderService {
private final PaymentProcessor paymentProcessor;
// Constructor Dependency Injection:
public OrderService(PaymentProcessor paymentProcessor) {
this.paymentProcessor = paymentProcessor;
}
}
Reference:
Spring Framework
Q 30
What is the Spring Framework and what is the difference between Spring Framework and Spring Boot?
Easy
Answer
Spring Framework is an enterprise Java framework providing IoC/DI, AOP, transaction management, and MVC architecture requiring manual XML or Java configuration. Spring Boot is an opinionated layer built on top of Spring that provides auto-configuration, embedded servers (Tomcat), and starter POMs to eliminate boilerplate setup.
Explanation
Spring provides the foundational framework and modular components; Spring Boot automates the configuration and packaging of Spring applications.
Code Example
Java
// Spring Framework: Explicit Java Config
@Configuration
@ComponentScan("com.example")
public class AppConfig {
@Bean
public UserService userService() {
return new UserServiceImpl(userDao());
}
@Bean
public UserDao userDao() {
return new UserDaoImpl();
}
}
Reference:
Spring Framework
About This Topic
Prepare for
Spring Framework interviews with important concepts
and commonly asked questions.