Java Interview Questions

Spring Framework Interview Questions

40 essential Spring Framework interview questions covering Core, Boot, MVC, Data, Security, AOP, and microservices.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

40 essential Spring Framework interview questions covering Core, Boot, MVC, Data, Security, AOP, and microservices. This interview-focused guide covers essential spring framework interview questions concepts for technical interviews.

Spring Framework Interview Questions

Spring is the most popular Java framework for enterprise development. These 40 questions cover Spring Core, Boot, MVC, Data JPA, Security, AOP, and cloud microservices patterns.


1. What is the Spring Framework?

Spring is a lightweight, open-source Java framework for building enterprise applications. It provides comprehensive infrastructure support with features like Dependency Injection (DI), Aspect-Oriented Programming (AOP), and modular architecture (Data, MVC, Security, etc.).

[!NOTE] Spring's core philosophy: "Don't repeat the work" — it handles boilerplate code so you focus on business logic.

2. What is Spring Boot?

Spring Boot simplifies Spring application development with auto-configuration, embedded servers (Tomcat/Jetty), and starter dependencies. It eliminates boilerplate XML configuration and gets applications running quickly.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3. What are the advantages of Spring Boot?

  • Auto-configuration: Configures beans based on classpath
  • Starter dependencies: Opinionated, simplified dependency management
  • Embedded servers: No external server needed (Tomcat, Jetty, Undertow)
  • Actuator: Production-ready monitoring endpoints
  • No XML: Java-based configuration
  • DevTools: Automatic restart, live reload

4. What is Dependency Injection (DI)?

Dependency Injection is a design pattern where objects receive their dependencies from outside rather than creating them internally. Spring handles this via the IoC (Inversion of Control) container.

@Service
public class OrderService {
    private final PaymentService paymentService;
    
    // Constructor Injection (preferred)
    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}

5. What is Inversion of Control (IoC)?

IoC means the framework controls the flow of the program, not your code. Spring's IoC container manages object creation, wiring, lifecycle, and configuration. The container uses DI to achieve IoC.

6. What is the Spring IoC Container?

The IoC Container is the core of Spring. It's responsible for:

  • Creating and managing beans
  • Wiring dependencies
  • Managing bean lifecycle
  • Two types: BeanFactory (basic) and ApplicationContext (advanced, preferred)

7. Difference between BeanFactory and ApplicationContext?

| Feature | BeanFactory | ApplicationContext | |---------|-------------|-------------------| | Lazy Loading | Yes (lazy) | Eager (by default) | | Internationalization | No | Yes (MessageSource) | | Event Publication | No | Yes | | AOP Support | Limited | Full | | Annotation Support | Limited | Full | | Usage | Memory-constrained | Standard enterprise apps |

8. What is a Spring Bean?

A Spring Bean is an object that is instantiated, assembled, and managed by the Spring IoC Container. Defined via @Component, @Bean, or XML configuration.

9. What are the bean scopes in Spring?

  • singleton (default): Single instance per container
  • prototype: New instance each time requested
  • request: New instance per HTTP request (web only)
  • session: New instance per HTTP session (web only)
  • application: Single instance per ServletContext
  • websocket: Per WebSocket session

10. What is the difference between singleton and prototype scope?

  • singleton: One bean instance shared across all requests. Most common. Thread-safety is your responsibility.
  • prototype: New bean instance created for every request. Use for stateful beans.

[!IMPORTANT] Spring does NOT manage the complete lifecycle of prototype beans. They're created but not destroyed by the container.

11. What is the Spring Bean lifecycle?

  1. Instantiate: Bean object created
  2. Populate properties: Dependencies injected
  3. setBeanName(): If BeanNameAware
  4. setBeanFactory(): If BeanFactoryAware
  5. PostProcessBeforeInitialization: BeanPostProcessor
  6. @PostConstruct: Init method
  7. InitializingBean.afterPropertiesSet()
  8. Custom init-method
  9. PostProcessAfterInitialization: BeanPostProcessor
  10. Bean is ready
  11. @PreDestroy: Destroy method
  12. DisposableBean.destroy()

12. What is @Component annotation?

@Component marks a Java class as a Spring bean. Component scanning (@ComponentScan) detects and registers these classes.

@Component
public class EmailService {
    // Spring manages this bean
}

13. What are stereotype annotations?

Spring provides more specific @Component variants:

  • @Service: Business logic layer
  • @Repository: Data access layer (adds exception translation)
  • @Controller: MVC controllers
  • @RestController: REST API controllers (@Controller + @ResponseBody)

14. What is @Autowired annotation?

@Autowired enables automatic dependency injection by Spring. It can be applied to constructors, setters, and fields. Constructor injection is preferred.

@Autowired
private UserRepository userRepository;  // Field injection (less preferred)

15. What are the types of Dependency Injection?

  1. Constructor Injection: Dependencies via constructor (preferred — immutable, testable)
  2. Setter Injection: Dependencies via setter methods (optional dependencies)
  3. Field Injection: Direct field injection via @Autowired (convenient but not recommended)

16. What is @Qualifier annotation?

@Qualifier resolves ambiguity when multiple beans of the same type exist. It specifies which bean to inject.

@Autowired
@Qualifier("emailService")
private NotificationService service;

17. What is @Primary annotation?

@Primary marks a bean as the default choice when multiple beans of the same type exist. Works with @Qualifier@Qualifier takes priority.

18. What is @Configuration and @Bean?

  • @Configuration: Marks a class as a configuration class (source of bean definitions)
  • @Bean: Marks a method that produces a bean managed by Spring
@Configuration
public class AppConfig {
    @Bean
    public DataSource dataSource() {
        return new HikariDataSource();
    }
}

19. What is @Value annotation?

@Value injects values from properties files, environment variables, or system properties.

@Value("${app.name}")
private String appName;

@Value("${server.port:8080}") // Default: 8080
private int port;

20. What is Spring Boot Auto-Configuration?

Auto-configuration automatically configures Spring beans based on:

  • Classpath dependencies (e.g., spring-boot-starter-web → embedded Tomcat)
  • Existing beans
  • Property files (application.properties/yml)

[!TIP] Use @ConditionalOnClass, @ConditionalOnMissingBean to control auto-configuration. Disable specific auto-config with @EnableAutoConfiguration(exclude=...).

21. What is @SpringBootApplication?

@SpringBootApplication combines three annotations:

  • @Configuration: Configuration class
  • @EnableAutoConfiguration: Enables auto-configuration
  • @ComponentScan: Scans for components in package and sub-packages

22. What is Spring MVC?

Spring MVC (Model-View-Controller) is a web framework for building web applications:

  • Model: Data (Java objects)
  • View: Presentation (JSP, Thymeleaf)
  • Controller: Business logic, handles requests
  • DispatcherServlet: Front controller routing all requests

23. How does Spring MVC handle a request?

  1. Request arrives at DispatcherServlet
  2. HandlerMapping finds the appropriate controller
  3. Controller processes request, returns ModelAndView
  4. ViewResolver resolves view name to actual view
  5. View renders the response

24. What is @RestController?

@RestController = @Controller + @ResponseBody. It returns data (JSON/XML) directly, not view names. Default behavior for REST APIs.

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) { ... }
}

25. What are common Spring MVC annotations?

  • @RequestMapping: Maps URL to controller/endpoint
  • @GetMapping / @PostMapping / @PutMapping / @DeleteMapping: HTTP method-specific
  • @PathVariable: Extract values from URL
  • @RequestParam: Extract query parameters
  • @RequestBody: Extract request body (JSON → Object)
  • @ResponseStatus: Custom HTTP status code

26. What is Spring Data JPA?

Spring Data JPA simplifies database access by reducing boilerplate code. It uses repositories (interfaces) to provide CRUD operations without implementation.

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByEmail(String email);
}

27. What is the difference between CrudRepository and JpaRepository?

  • CrudRepository: Basic CRUD operations
  • JpaRepository: Extends CrudRepository. Adds JPA-specific features: batch operations, pagination, sorting, and flushing.

28. What is @Entity annotation?

@Entity marks a class as a JPA entity that maps to a database table. The class must have a no-arg constructor and a primary key.

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

29. What is @Transactional?

@Transactional declares that a method (or class) executes within a transaction. It manages transaction boundaries declaratively.

@Transactional
public void transfer(Account from, Account to, BigDecimal amount) {
    from.debit(amount);
    to.credit(amount);
    // If exception: rollback both
}

30. What is transaction propagation?

Transaction propagation defines how transactions relate to each other:

  • REQUIRED (default): Use existing or create new
  • REQUIRES_NEW: Suspend existing, create new
  • MANDATORY: Must have existing transaction
  • SUPPORTS: Use if exists, non-transactional otherwise
  • NOT_SUPPORTED: Execute non-transactionally

31. What is Spring AOP?

Aspect-Oriented Programming (AOP) separates cross-cutting concerns (logging, security, transactions) from business logic. AOP applies "aspects" around method calls.

32. What are AOP concepts?

  • Aspect: Module of cross-cutting concern (@Aspect)
  • Advice: Action taken at joinpoint (@Before, @After, @Around)
  • Joinpoint: Point where aspect can be applied (method execution)
  • Pointcut: Expression selecting joinpoints
  • Weaving: Linking aspects with objects

33. What are the types of Advice?

  • @Before: Execute before joinpoint
  • @After: Execute after joinpoint (regardless of outcome)
  • @AfterReturning: Execute after successful return
  • @AfterThrowing: Execute after exception thrown
  • @Around: Wraps joinpoint (most powerful)

34. What is Spring Security?

Spring Security provides authentication, authorization, and protection against common attacks. It's a powerful and customizable security framework.

35. How does Spring Security work?

Spring Security uses a filter chain to intercept requests:

  1. AuthenticationFilter validates credentials
  2. AuthenticationManager processes authentication
  3. SecurityContext holds authenticated user
  4. Authorization checks access based on roles/permissions

36. What is JWT (JSON Web Token)?

JWT is a compact, URL-safe token for stateless authentication. Contains header, payload, and signature. Spring Security can validate and parse JWTs.

37. What is application.properties vs application.yml?

Both configure Spring Boot. YAML is hierarchical, more readable for complex configs. Properties uses key=value format. Both are supported equally.

38. What are Spring Boot Actuator endpoints?

Actuator provides production-ready features:

  • /health - Application health
  • /info - Application info
  • /metrics - Application metrics
  • /env - Environment properties
  • /loggers - Logger configuration
  • /mappings - Request mappings

39. What is Spring Cloud?

Spring Cloud provides tools for building distributed/microservices systems:

  • Service Discovery (Eureka)
  • API Gateway (Spring Cloud Gateway)
  • Config Server
  • Circuit Breaker (Resilience4j)
  • Load Balancing (Spring Cloud LoadBalancer)

40. What is the difference between @Component, @Service, and @Repository?

All three register beans, but:

  • @Component: Generic stereotype for any Spring bean
  • @Service: Business logic layer; semantically clearer
  • @Repository: DAO layer; adds persistence exception translation (converts JPA/Hibernate exceptions to Spring DataAccessException)
JAVA PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Spring Framework interview questions covering Core, Boot, MVC, Data, Security, and microservices"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 3

What is the default scope of a Spring bean?

prototype
singleton
request
session