■ Spring Boot
Annotations
Interview Guide
29 Most Asked Questions with Detailed Answers
Easy → Medium → Hard
■ 10 Easy ■ 10 Medium ■ 9 Hard
Easy = Expected • Medium = Shortlisted • Hard = Selected ■
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations
Spring Boot Annotations — Interview Guide Page 2
■ EASY — Foundation (Must Be Perfect)
Q1 What is @SpringBootApplication?
Marks the main class of a Spring Boot application. It's a convenience annotation that combines three
annotations into one, enabling auto-configuration, component scanning, and configuration support.
Q2 What is Components of @SpringBootApplication?
It combines:
• @SpringBootConfiguration — marks the class as a source of bean definitions (extends
@Configuration)
• @EnableAutoConfiguration — tells Spring Boot to auto-configure beans based on classpath
dependencies
• @ComponentScan — scans the current package and sub-packages for @Component, @Service,
@Repository, @Controller beans
Q3 What is @Component?
A generic stereotype annotation used to mark a Java class as a Spring-managed bean. Spring's
component scanning detects it and registers it in the ApplicationContext automatically.
@Component
public class EmailValidator { ... }
Q4 @Component vs @Service vs @Repository
All three are specializations of @Component (functionally equivalent for bean creation), but differ in
semantics:
• @Component — generic Spring-managed bean
• @Service — marks business/service layer logic; improves readability
• @Repository — marks DAO/persistence layer; additionally enables Spring's exception translation
(DataAccessException)
Q5 What is @Autowired?
Enables dependency injection. Spring automatically resolves and injects the collaborating bean. Can be
applied on constructor, setter, or field. Spring 4.3+ makes it optional on single-constructor classes.
■ Prefer constructor injection over field injection for testability and immutability.
Q6 What is @RestController?
A specialized @Controller used for RESTful web services. It combines @Controller + @ResponseBody,
meaning every method's return value is automatically serialized to JSON/XML and written to the HTTP
response body.
Q7 @Controller vs @RestController
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations
Spring Boot Annotations — Interview Guide Page 3
• @Controller — returns view names (MVC); needs @ResponseBody on methods to return JSON
• @RestController — all methods implicitly have @ResponseBody; returns data directly (JSON/XML)
— ideal for REST APIs
Q8 What is @RequestMapping?
Maps HTTP requests to handler methods or classes. Can specify URL path, HTTP method, headers,
params, and media types. Modern Spring prefers shorthand annotations.
@RequestMapping(value="/users", method=[Link])
Q9 What is @GetMapping / @PostMapping?
Shorthand composed annotations built on top of @RequestMapping:
• @GetMapping → GET requests (read data)
• @PostMapping → POST requests (create data)
• Also: @PutMapping, @PatchMapping, @DeleteMapping
Q10 What is @PathVariable?
Binds a URI template variable to a method parameter. Used when part of the URL itself carries the data
(e.g., /users/{id}).
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations
Spring Boot Annotations — Interview Guide Page 4
■ MEDIUM — Real Interview Level
Q11 Constructor vs Field Injection
Constructor Injection (Preferred):
• Dependencies declared as final — immutable
• Easy to unit-test (no Spring context needed)
• Fails fast on startup if dependency is missing
Field Injection (@Autowired on field):
• Concise but hides dependencies
• Hard to test without Spring
• Cannot declare fields as final
■ Always prefer constructor injection in production code.
Q12 What is @Qualifier?
When multiple beans of the same type exist, @Qualifier specifies which bean to inject, used alongside
@Autowired.
@Autowired
@Qualifier("emailNotificationService")
private NotificationService service;
Q13 What is @Primary?
Marks a bean as the default candidate when multiple beans of the same type exist. @Qualifier always
overrides @Primary if specified.
@Bean @Primary
public DataSource primaryDataSource() { ... }
Q14 @Bean vs @Component
• @Component — class-level; Spring auto-detects via classpath scan; you own the class
• @Bean — method-level inside a @Configuration class; used for third-party classes you don't own, or
when you need fine-grained control over instantiation
Q15 What is @Configuration?
Marks a class as a source of bean definitions. Methods annotated with @Bean inside it are managed by
Spring. @SpringBootConfiguration (used by @SpringBootApplication) is a meta-annotation of
@Configuration.
Q16 @RequestParam vs @RequestBody
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations
Spring Boot Annotations — Interview Guide Page 5
• @RequestParam — reads query parameters or form data from the URL (?key=value)
• @RequestBody — reads and deserializes the entire HTTP request body (JSON/XML) into a Java
object
// @RequestParam: GET /search?name=John
// @RequestBody: POST /users with JSON body
Q17 What is @ResponseBody?
Tells Spring to serialize the return value of a method directly to the HTTP response body (instead of
resolving a view name). Automatically included in @RestController.
Q18 What is @Valid and Validation?
Triggers Bean Validation (JSR-380) on a method parameter. Annotate fields with constraints like @NotNull,
@Size, @Email, then use @Valid on the controller parameter. A MethodArgumentNotValidException is
thrown on failure.
public ResponseEntity addUser(@Valid @RequestBody UserDto dto) { ... }
Q19 What is @ExceptionHandler?
Defines a method in a controller (or @ControllerAdvice) to handle specific exceptions thrown within that
controller. Returns a custom error response.
@ExceptionHandler([Link])
public ResponseEntity handleNotFound(UserNotFoundException ex) { ... }
Q20 What is @ControllerAdvice?
A global exception handling mechanism. Applied to a class, it intercepts exceptions across ALL controllers.
Combine with @ExceptionHandler methods to centralize error handling. @RestControllerAdvice adds
@ResponseBody implicitly.
■ Best practice: Use @RestControllerAdvice for REST APIs to return consistent JSON error responses.
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations
Spring Boot Annotations — Interview Guide Page 6
■ HARD — Where Most People Fail
Q21 What is @Transactional & Propagation?
Manages database transactions declaratively. Spring creates a proxy around the method.
Key Propagation types:
• REQUIRED (default) — joins existing tx or creates new one
• REQUIRES_NEW — always creates a new tx, suspends existing
• NESTED — runs within a nested tx (savepoint)
• MANDATORY — must run within an existing tx; throws if none
• NEVER — must NOT run in a tx; throws if one exists
• NOT_SUPPORTED — suspends existing tx and runs non-transactionally
• SUPPORTS — runs in tx if exists, otherwise non-transactionally
■ @Transactional only intercepts public methods via proxy. Self-invocation bypasses the proxy!
Q22 What is @Entity & Internal Mapping?
Marks a class as a JPA entity mapped to a database table. JPA uses the entity metadata to generate SQL.
Internally, Hibernate (default JPA provider) creates a SessionFactory, maps fields to columns, and
manages the persistence context.
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
}
Q23 What is @Table?
Specifies the table name and schema for an @Entity. Optional — if omitted, the class name is used as the
table name. Also allows defining unique constraints.
@Entity
@Table(name="users", schema="app",
uniqueConstraints=@UniqueConstraint(columnNames="email"))
public class User { ... }
Q24 What is @Id and @GeneratedValue Strategies?
@Id marks the primary key field.
@GeneratedValue strategies:
• AUTO (default) — JPA picks strategy based on DB
• IDENTITY — uses DB auto-increment (MySQL, PostgreSQL serial)
• SEQUENCE — uses DB sequence object (Oracle, PostgreSQL — preferred for performance)
• TABLE — uses a dedicated table to simulate sequences (portable but slow)
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations
Spring Boot Annotations — Interview Guide Page 7
■ Use SEQUENCE with allocationSize > 1 for high-throughput apps to batch ID allocation.
Q25 What is @OneToMany and @ManyToOne?
Model relational associations between entities:
• @ManyToOne — many records reference one parent; owns the FK column
• @OneToMany(mappedBy=...) — inverse side; 'mappedBy' points to the owning field
Always set mappedBy on the @OneToMany side to avoid duplicate join tables.
@ManyToOne
@JoinColumn(name="dept_id")
private Department department;
@OneToMany(mappedBy="department")
private List<Employee> employees;
Q26 [Link] vs EAGER
• EAGER — related entity loaded immediately with the parent query (additional JOIN). @ManyToOne
and @OneToOne default to EAGER.
• LAZY — related entity loaded only when accessed. @OneToMany and @ManyToMany default to
LAZY.
When to use LAZY: Almost always — avoids N+1 and unnecessary data loading.
When to use EAGER: Only when you always need the associated data and it's small.
■ LAZY on @ManyToOne can cause LazyInitializationException outside a session — use JOIN FETCH in JPQL or
@Transactional.
Q27 @Value vs @ConfigurationProperties
• @Value("${key}") — injects a single property; supports SpEL; less refactor-friendly
• @ConfigurationProperties(prefix="app") — binds a group of properties to a POJO; type-safe;
supports validation with @Valid; better for large config sets
■ Prefer @ConfigurationProperties for anything more than 1–2 properties.
Q28 What is @EnableAutoConfiguration?
Instructs Spring Boot to automatically configure beans based on classpath contents, other beans, and
property settings. Uses [Link] / [Link] to discover META-INF configuration
classes. You can exclude specific auto-configs with exclude attribute.
@SpringBootApplication(exclude = {[Link]})
Q29 What is How Spring Boot Auto-Configuration Works Internally?
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations
Spring Boot Annotations — Interview Guide Page 8
1. @EnableAutoConfiguration triggers AutoConfigurationImportSelector
2. It reads META-INF/spring/[Link] (Boot 3+)
3. Each listed class is a @Configuration class with @ConditionalOnClass, @ConditionalOnMissingBean,
etc.
4. Conditions are evaluated — beans are registered only if conditions pass
5. Example: If H2 is on classpath AND no DataSource bean exists → DataSourceAutoConfiguration creates
an in-memory DataSource
■ Run with --debug flag or set [Link]=DEBUG to see condition
evaluation report.
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations
Spring Boot Annotations — Interview Guide Page 9
■ Quick Revision Checklist
■ EASY — Must Score 10/10
Core annotations: @SpringBootApplication, @Component, @Autowired, @RestController
HTTP mappings: @GetMapping, @PostMapping, @PathVariable
■ MEDIUM — Aim for 8+/10
DI: Constructor injection, @Qualifier, @Primary
Validation & Exception: @Valid, @ExceptionHandler, @ControllerAdvice
■ HARD — Know at Least 7/9
JPA: @Transactional propagation, FetchType LAZY/EAGER, @GeneratedValue
Config: @Value vs @ConfigurationProperties, Auto-Configuration internals
Good luck in your interview! ■ Save this PDF and revise before every interview.
Free Interview Prep Guide • 29 Must-Know Spring Boot Annotations