0% found this document useful (0 votes)
0 views10 pages

Spring SpringBoot Interview Questions.md

The document provides a comprehensive overview of Spring and Spring Boot, including key concepts such as Inversion of Control, Dependency Injection, Spring Beans, and their lifecycle. It also compares Spring with Spring Boot, explains various annotations, and outlines Spring Boot's auto-configuration, starters, and testing annotations. Additionally, it touches on Spring Security and microservices, making it a valuable resource for interview preparation in this domain.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views10 pages

Spring SpringBoot Interview Questions.md

The document provides a comprehensive overview of Spring and Spring Boot, including key concepts such as Inversion of Control, Dependency Injection, Spring Beans, and their lifecycle. It also compares Spring with Spring Boot, explains various annotations, and outlines Spring Boot's auto-configuration, starters, and testing annotations. Additionally, it touches on Spring Security and microservices, making it a valuable resource for interview preparation in this domain.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Spring & Spring Boot Interview Questions (Easy–Medium)

1. What is the Spring Framework? Why use it?


Spring is a lightweight, open-source Java framework that provides infrastructure support
for building enterprise applications. Its core value comes from:
IoC / Dependency Injection — objects don't create their own dependencies; the
container provides them
AOP (Aspect-Oriented Programming) — separates cross-cutting concerns (logging,
security, transactions) from business logic
Loose coupling — components depend on abstractions, not concrete
implementations, making code easier to test and maintain
Modular — you only pull in the modules you need (Core, MVC, Data, Security, etc.)
POJO-based — you don't need to extend framework-specific classes
2. Spring vs Spring Boot
Spring Spring Boot

Requires manual configuration (XML or Java Auto-configures based on classpath


config) dependencies

No embedded server — needs external Comes with an embedded server (Tomcat by


Tomcat/Jetty default)

More boilerplate to get started "Convention over configuration" — minimal


setup

Dependency versions managed manually Starter POMs manage compatible dependency


versions

Good for fine-grained control Good for rapid development, especially


microservices

Spring Boot is built on top of Spring — it doesn't replace it, it removes the setup friction.

3. Inversion of Control (IoC) and Dependency Injection (DI)


IoC is the principle: instead of your code creating and wiring objects with new , control is
handed to a container (the Spring IoC container), which creates, configures, and wires
objects for you.
DI is how Spring implements IoC — dependencies are "injected" into a class rather than the
class instantiating them itself.
Types of Dependency Injection

java

// Constructor Injection (recommended — supports immutability, easy to unit tes


@Service
public class OrderService {
private final PaymentGateway paymentGateway;

@Autowired
public OrderService(PaymentGateway paymentGateway) {
[Link] = paymentGateway;
}
}

// Setter Injection (good for optional dependencies)


@Service
public class OrderService {
private PaymentGateway paymentGateway;

@Autowired
public void setPaymentGateway(PaymentGateway paymentGateway) {
[Link] = paymentGateway;
}
}

// Field Injection (concise but considered an anti-pattern — hides dependencies


@Service
public class OrderService {
@Autowired
private PaymentGateway paymentGateway;
}
 

Interview tip: Constructor injection is the generally preferred approach — it makes


dependencies explicit, allows final fields, and lets Spring fail fast at startup if a
dependency is missing.

4. What is a Spring Bean?


A bean is simply an object that is instantiated, assembled, and managed by the Spring IoC
container. Instead of you writing new MyService() , you tell Spring (via annotations or
config) what you need, and the container hands you a fully-wired instance.
5. Spring Bean Lifecycle
1. Instantiation — container creates the bean instance
2. Populate properties — dependencies are injected
3. Aware interfaces called (if implemented) — e.g., BeanNameAware ,
ApplicationContextAware
4. BeanPostProcessor (before init)
5. Initialization — @PostConstruct method or custom init() runs
6. BeanPostProcessor (after init)
7. Bean is ready for use
8. Destruction — @PreDestroy or custom destroy() runs when the context closes

java

@Component
public class CacheManager {
@PostConstruct
public void init() { [Link]("Cache initialized"); }

@PreDestroy
public void cleanup() { [Link]("Cache cleared"); }
}

6. Bean Scopes
Scope Description

singleton (default) One shared instance per Spring container

prototype New instance every time the bean is requested

request One instance per HTTP request (web-aware contexts only)

session One instance per HTTP session

application One instance per ServletContext

java

@Component
@Scope("prototype")
public class ShoppingCart { }

7. BeanFactory vs ApplicationContext
BeanFactory: the basic container — lazy initialization, minimal features
ApplicationContext: extends BeanFactory — adds eager initialization by default,
event publishing, internationalization, AOP integration, and easier annotation-based
configuration
In practice, almost every real application uses ApplicationContext (or Spring Boot's auto-
created one) rather than BeanFactory directly.

8. @Component vs @Service vs @Repository vs @Controller


All four are stereotype annotations that register a class as a Spring bean via component
scanning — functionally similar, but semantically different:

Annotation Purpose

@Component Generic stereotype — any Spring-managed component

@Service Marks a business/service-layer class

@Repository Marks a data-access layer class; also enables automatic translation of


persistence exceptions into Spring's DataAccessException

@Controller Marks a web controller (returns view names)

@RestController @Controller + @ResponseBody — returns data (JSON/XML) directly as


the response body

9. @Controller vs @RestController
@Controller is used in traditional Spring MVC apps returning view templates (e.g.,
Thymeleaf/JSP)
@RestController = @Controller + @ResponseBody , so every method's return value is
serialized directly into the HTTP response body — the standard choice for REST APIs

java

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

@GetMapping
public List<Employee> getAll() { return [Link](); }

@GetMapping("/{id}")
public Employee getById(@PathVariable Long id) { return [Link]

@PostMapping
public Employee create(@RequestBody Employee employee) { return employeeSer
}
 
10. @RequestMapping vs @GetMapping / @PostMapping etc.
@RequestMapping is the general-purpose mapping annotation (you specify the HTTP
method via an attribute). @GetMapping , @PostMapping , @PutMapping , @DeleteMapping , and
@PatchMapping are shorthand, method-specific versions of @RequestMapping introduced for
readability.

java

@RequestMapping(value = "/hello", method = [Link]) // verbose


@GetMapping("/hello") // equivalent, c
 

11. @PathVariable vs @RequestParam


@PathVariable extracts a value from the URI path itself ( /employees/{id} )
@RequestParam extracts a value from query parameters ( /employees?dept=IT )

java

@GetMapping("/employees/{id}")
public Employee getEmployee(@PathVariable Long id) { ... }

@GetMapping("/employees")
public List<Employee> search(@RequestParam String dept) { ... }

12. @RequestBody vs @ResponseBody


@RequestBody binds the incoming HTTP request body (typically JSON) to a Java
object
@ResponseBody tells Spring to serialize the returned Java object directly into the HTTP
response body instead of resolving it as a view name
13. @Autowired vs @Qualifier vs @Primary
@Autowired tells Spring to inject a bean automatically by type
If multiple beans of the same type exist, Spring doesn't know which one to pick — this
causes ambiguity
@Qualifier("beanName") resolves that ambiguity by specifying exactly which bean to
inject
@Primary marks one bean as the default choice when multiple candidates exist — but
@Qualifier , when present, always takes precedence over @Primary

java
public interface PaymentGateway { }

@Component("paypal")
public class PaypalGateway implements PaymentGateway { }

@Component("stripe")
@Primary
public class StripeGateway implements PaymentGateway { }

@Service
public class CheckoutService {
@Autowired
@Qualifier("paypal") // wins over @Primary
private PaymentGateway gateway;
}

14. What is @SpringBootApplication?


A convenience annotation that bundles three annotations together:
@Configuration — marks the class as a source of bean definitions
@ComponentScan — scans the package (and sub-packages) for Spring-managed
components
@EnableAutoConfiguration — triggers Spring Boot's auto-configuration mechanism
15. How does Spring Boot Auto-Configuration work?
When the app starts, @EnableAutoConfiguration scans configuration classes registered by
starter dependencies and conditionally applies them based on what's present on the
classpath and what beans already exist in the context. For example, if spring-boot-starter-
data-jpa and a database driver are on the classpath and [Link] has
datasource settings, Spring Boot automatically configures a DataSource bean — you don't
wire it manually. This conditional logic is driven by annotations like @ConditionalOnClass ,
@ConditionalOnMissingBean , and @ConditionalOnProperty .

16. What are Spring Boot Starters?


Starters are curated dependency descriptors (e.g., spring-boot-starter-web , spring-boot-
starter-data-jpa , spring-boot-starter-security ) that pull in a set of compatible libraries
with pre-tested versions, so you don't have to manually manage version conflicts.
17. [Link] vs [Link]
Both configure the application externally (server port, DB credentials, logging levels, etc.).
.properties uses flat key-value pairs ( [Link]=8081 ); .yml uses nested, indentation-
based structure, which many find cleaner for hierarchical configuration.
18. Embedded Servers & Default Port
Spring Boot embeds a servlet container (Tomcat by default, or Jetty/Undertow if swapped
in) so the app runs as a standalone JAR without needing an external server install. The
default port is 8080, overridden via:

properties

[Link]=9090

19. Spring Boot Actuator


A production-readiness module that exposes operational endpoints out of the box — e.g.,
/actuator/health , /actuator/metrics , /actuator/info — for monitoring, health checks,
and diagnostics without writing custom code.

20. Exception Handling: @ExceptionHandler, @ControllerAdvice,


@RestControllerAdvice
@ExceptionHandler — handles a specific exception type within a single controller
@ControllerAdvice — applies exception handling (and other advice) globally, across
all controllers
@RestControllerAdvice — @ControllerAdvice + @ResponseBody , the standard choice
for global exception handling in REST APIs

java

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler([Link])
public ResponseEntity<String> handleNotFound(EmployeeNotFoundException ex)
return [Link](HttpStatus.NOT_FOUND).body([Link]()
}
}
 

21. @Transactional
Marks a method (or class) so its database operations run within a single transaction — if an
unchecked exception occurs, the transaction is rolled back automatically, keeping the data
consistent.

java
@Service
public class UserService {
@Transactional
public void createUser(User user) {
[Link](user);
}
}

22. Spring Data JPA Basics


@Entity — marks a class as a JPA-mapped database table
@Id — marks the primary key field
Extending JpaRepository<Entity, IdType> gives you CRUD methods ( save ,
findById , findAll , deleteById ) for free, with no implementation code required

Custom queries can be derived from method names ( findByLastName ) or written


explicitly with @Query

java

public interface EmployeeRepository extends JpaRepository<Employee, Long> {


List<Employee> findByDepartment(String department);
}

23. Bean Validation


Fields on request/model objects can be validated declaratively using annotations like
@NotNull , @NotBlank , @Size , @Min , @Max , @Email , paired with @Valid on the controller
parameter. Violations are captured via BindingResult or automatically converted into a 400
Bad Request response.

24. @Profile
Lets you activate different bean configurations for different environments (dev, test, prod):

java

@Configuration
@Profile("dev")
public class DevConfig { ... }

Activated via [Link]=dev in configuration or as a startup argument.


25. Spring Boot Testing Annotations
Annotation Purpose

@SpringBootTest Loads the full application context — for integration tests

@WebMvcTest Loads only the web layer (controllers) — faster, sliced test

@DataJpaTest Loads only JPA-related components — for repository tests

@MockBean Replaces a bean in the context with a Mockito mock

26. Spring Security — the basics


Authentication: verifying who the user is (e.g., username/password, JWT, OAuth2)
Authorization: verifying what the authenticated user is allowed to do
(roles/permissions)
Spring Security works via a filter chain — every request passes through a series of
filters before reaching the controller, where authentication and authorization checks
happen
@PreAuthorize("hasRole('ADMIN')") is a common way to secure individual methods

27. Spring Boot & Microservices


Spring Boot is widely used to build microservices because of its fast startup, embedded
servers, and minimal configuration — each service can be developed, deployed, and scaled
independently. Common companion tools in the ecosystem: Spring Cloud (config server,
service discovery), Eureka (service registry), Feign/RestTemplate/WebClient (inter-
service calls), and API Gateway patterns for routing.
Quick-Fire Differences (common trap questions)
Question Short Answer

@Component vs @Bean @Component is a class-level annotation for auto-detection via


scanning; @Bean is a method-level annotation inside a
@Configuration class for manually declaring a bean, often used for
third-party classes you can't annotate directly

@Qualifier vs @Qualifier wins


@Primary when both
present

Constructor vs Field Constructor is preferred — immutability, explicit dependencies, easier


injection testing

@RequestMapping vs Same underlying mechanism; @GetMapping is shorthand restricted


@GetMapping to GET

Singleton (Spring) vs Spring's singleton is one instance per container, not one per JVM — a
Singleton (GoF pattern) subtle but common gotcha

Interview tip
Many mid-level rounds combine these — e.g., "walk me through what happens when a
REST request hits your @RestController until the response is returned," which touches
DispatcherServlet routing, dependency-injected service/repository layers, JPA, and
exception handling all in one answer. Practice narrating that end-to-end flow out loud.

You might also like