Spring Boot Annotations — Master List
Topic 1: Application Bootstrap
1. @SpringBootApplication
- Bootstraps the entire Spring Boot application
- Parameters:
scanBasePackages(packages to scan),exclude(auto-configs to disable) - Example:
@SpringBootApplication(scanBasePackages = "com.akash")
2. @Configuration
- Marks a class as a source of bean definitions
- Parameters:
proxyBeanMethods(default: true) - Example:
@Configuration public class AppConfig {}
3. @ComponentScan
- Tells Spring which packages to scan for beans
- Parameters:
basePackages,excludeFilters,includeFilters - Example:
@ComponentScan(basePackages = "com.akash")
4. @EnableAutoConfiguration
- Auto-configures beans based on classpath dependencies
- Parameters:
exclude(disable specific auto-configs),excludeName - Example:
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
Topic 2: Bean Annotations
5. @Component
- Generic stereotype to register any class as a Spring bean
- Parameters:
value(custom bean name, default: className in camelCase) - Example:
@Component("emailSvc") public class EmailService {}
6. @Service
- Specialization of
@Componentfor the business/service layer - Parameters:
value(custom bean name) - Example:
@Service public class UserService {}
7. @Repository
- Specialization of
@Componentfor data access layer; adds exception translation - Parameters:
value(custom bean name) - Example:
@Repository public class UserRepository {}
8. @Controller
- Marks an MVC controller that handles web requests and returns view names
- Parameters:
value(custom bean name) - Example:
@Controller public class UserController {}
9. @RestController
- Combines
@Controller+@ResponseBody; returns JSON/XML directly - Parameters:
value(custom bean name) - Example:
@RestController public class UserApi {}
10. @Bean
- Manually declares a method's return value as a Spring bean
- Parameters:
name(bean name),initMethod,destroyMethod - Example:
@Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }
Topic 3: Scope & Lifecycle
11. @Scope
- Controls how many instances Spring creates for a bean
- Parameters:
value(singleton / prototype / request / session),proxyMode - Example:
@Scope("prototype")
12. @PostConstruct
- Method runs once after dependency injection is complete
- Parameters: none
- Example:
@PostConstruct public void init() { loadCache(); }
13. @PreDestroy
- Method runs just before the bean is removed from the container
- Parameters: none
- Example:
@PreDestroy public void cleanup() { connection.close(); }
Topic 4: Dependency Injection
14. @Autowired
- Injects a matching bean automatically from the Spring container
- Parameters:
required(throw exception if no bean found, default: true) - Example:
@Autowired private UserRepository repository;
15. @Primary
- Marks one bean as the default when multiple candidates of the same type exist
- Parameters: none
- Example:
@Primary @Component public class MySqlDatabase implements Database {}
16. @Qualifier
- Explicitly names which bean to inject when multiple candidates exist
- Parameters:
value(bean name to inject — required) - Example:
@Autowired @Qualifier("oracleDatabase") private Database db;
17. @Lazy
- Delays bean creation until it is first accessed
- Parameters:
value(true = lazy, false = eager, default: true) - Example:
@Lazy @Component public class HeavyReportService {}
18. @Value
- Injects a value from
application.propertiesor a hardcoded literal - Parameters:
value(property placeholder or SpEL expression — required) - Example:
@Value("${app.name}") private String appName;
19. @ConditionalOnProperty
- Registers a bean only when a property exists and matches a given value
- Parameters:
name(property key),havingValue,matchIfMissing(default: false),prefix - Example:
@ConditionalOnProperty(name = "app.cache.enabled", havingValue = "true")
Topic 5: Spring MVC & RESTful APIs — Presentation Layer
20. @RequestMapping
- Maps HTTP requests to a controller class or method; base path for all routes in a controller
- Parameters:
value/path(URL),method(GET/POST etc.),produces,consumes - Example:
@RequestMapping("/api/users")
21. @ResponseBody
- Tells Spring to serialize the return value directly to HTTP response body as JSON/XML
- Parameters: none
- Example:
@ResponseBody public User getUser() { return user; }
22. @GetMapping
- Handles HTTP GET requests; used to fetch/read data
- Parameters:
value/path(URL),produces,params,headers - Example:
@GetMapping("/users/{id}")
23. @PostMapping
- Handles HTTP POST requests; used to create new resources
- Parameters:
value/path(URL),consumes,produces - Example:
@PostMapping("/users")
24. @PutMapping
- Handles HTTP PUT requests; used to replace an entire resource
- Parameters:
value/path(URL),consumes,produces - Example:
@PutMapping("/users/{id}")
25. @PatchMapping
- Handles HTTP PATCH requests; used to partially update a resource
- Parameters:
value/path(URL),consumes,produces - Example:
@PatchMapping("/users/{id}")
26. @DeleteMapping
- Handles HTTP DELETE requests; used to remove a resource
- Parameters:
value/path(URL),produces - Example:
@DeleteMapping("/users/{id}")
27. @PathVariable
- Extracts a value from the URL path and binds it to a method parameter
- Parameters:
value(path variable name),required(default: true) - Example:
@GetMapping("/users/{id}") public User get(@PathVariable Long id)
28. @RequestParam
- Extracts a query parameter from the URL and binds it to a method parameter
- Parameters:
value(param name),required(default: true),defaultValue - Example:
@GetMapping("/users") public List<User> search(@RequestParam String name)
29. @RequestBody
- Deserializes the HTTP request body (JSON/XML) into a Java object
- Parameters:
required(default: true) - Example:
@PostMapping("/users") public User create(@RequestBody UserDto dto)
Topic 6: Persistence Layer & JPA
30. @Entity
- Marks a class as a JPA entity mapped to a database table
- Parameters:
name(entity name, default: class name) - Example:
@Entity public class User {}
31. @Table
- Specifies the database table name and schema for an entity
- Parameters:
name(table name),schema,catalog,uniqueConstraints - Example:
@Table(name = "departments")
32. @Id
- Marks a field as the primary key of the entity
- Parameters: none
- Example:
@Id private Long id;
33. @GeneratedValue
- Defines the strategy for auto-generating primary key values
- Parameters:
strategy(AUTO / IDENTITY / SEQUENCE / TABLE),generator - Example:
@GeneratedValue(strategy = GenerationType.IDENTITY)
34. @Column
- Maps a field to a specific database column with custom constraints
- Parameters:
name,nullable(default: true),unique,length,insertable,updatable - Example:
@Column(name = "email", nullable = false, unique = true)
35. @OneToMany
- Defines a one-to-many relationship between two entities
- Parameters:
mappedBy,cascade,fetch(LAZY/EAGER),orphanRemoval - Example:
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
36. @ManyToOne
- Defines a many-to-one relationship between two entities
- Parameters:
fetch(default: EAGER),cascade,optional - Example:
@ManyToOne @JoinColumn(name = "dept_id") private Department dept;
37. @JoinColumn
- Specifies the foreign key column for a relationship
- Parameters:
name(column name),nullable,unique,referencedColumnName - Example:
@JoinColumn(name = "department_id")
Topic 7: Lombok Annotations
38. @Getter
- Auto-generates getter methods for all fields (or a specific field)
- Parameters:
value(access level: PUBLIC/PROTECTED/PRIVATE, default: PUBLIC) - Example:
@Getter public class User { private String name; }
39. @Setter
- Auto-generates setter methods for all fields (or a specific field)
- Parameters:
value(access level, default: PUBLIC) - Example:
@Setter public class User { private String name; }
40. @AllArgsConstructor
- Generates a constructor with one parameter for every field
- Parameters:
access(access level),staticName(creates static factory method) - Example:
@AllArgsConstructor public class User {}
41. @NoArgsConstructor
- Generates a no-argument constructor (required by JPA)
- Parameters:
access(access level),force(initializes final fields to defaults) - Example:
@NoArgsConstructor public class User {}
42. @RequiredArgsConstructor
- Generates a constructor only for
finaland@NonNullfields - Parameters:
access,staticName - Example:
@RequiredArgsConstructor public class UserService {}
43. @Data
- Shortcut for
@Getter+@Setter+@ToString+@EqualsAndHashCode+@RequiredArgsConstructor - Parameters:
staticConstructor - Example:
@Data public class UserDto {}
44. @Builder
- Generates a builder pattern for the class
- Parameters:
toBuilder(add toBuilder() method),builderClassName,buildMethodName - Example:
@Builder public class User {}→User.builder().name("Akash").build()
45. @ToString
- Generates a
toString()method - Parameters:
exclude(fields to skip),includeFieldNames(default: true),callSuper - Example:
@ToString(exclude = "password")
Topic 8: JSON Annotations
46. @JsonProperty
- Maps a Java field to a different JSON key name during serialization/deserialization
- Parameters:
value(JSON key name),access(READ_ONLY / WRITE_ONLY / READ_WRITE) - Example:
@JsonProperty("full_name") private String fullName;
47. @JsonIgnore
- Excludes a field from both serialization and deserialization
- Parameters:
value(default: true) - Example:
@JsonIgnore private String password;
48. @JsonIgnoreProperties
- Ignores unknown JSON properties or specified fields at class level
- Parameters:
value(field names to ignore),ignoreUnknown(default: false) - Example:
@JsonIgnoreProperties(ignoreUnknown = true)
49. @JsonInclude
- Controls when a field is included in serialization (e.g. skip nulls)
- Parameters:
value(NON_NULL / NON_EMPTY / ALWAYS / NON_DEFAULT) - Example:
@JsonInclude(JsonInclude.Include.NON_NULL)
50. @JsonFormat
- Specifies format for dates, numbers, or enums during serialization
- Parameters:
shape,pattern(date pattern),timezone - Example:
@JsonFormat(pattern = "yyyy-MM-dd") private LocalDate dob;
Topic 9: Validation Annotations
51. @Valid
- Triggers validation on a method parameter (cascades into nested objects)
- Parameters: none
- Example:
public User create(@Valid @RequestBody UserDto dto)
52. @Validated
- Spring's variant of
@Valid; supports group-based validation - Parameters:
value(validation groups) - Example:
@Validated(OnCreate.class)
53. @NotNull
- Field must not be null (empty string is allowed)
- Parameters:
message(custom error message),groups - Example:
@NotNull(message = "Name is required") private String name;
54. @Null
- Field must be null (rarely used, mainly for update-group scenarios)
- Parameters:
message,groups - Example:
@Null private Long id;
55. @NotEmpty
- Field must not be null and must have at least one character / element
- Parameters:
message,groups - Example:
@NotEmpty private String username;
56. @NotBlank
- Field must not be null, empty, or whitespace only (stricter than
@NotEmpty) - Parameters:
message,groups - Example:
@NotBlank private String email;
57. @Pattern
- Field must match a given regular expression
- Parameters:
regexp(regex — required),flags,message - Example:
@Pattern(regexp = "^[0-9]{10}$") private String phone;
58. @Size
- Validates length of strings, arrays, or collections
- Parameters:
min(default: 0),max(default: Integer.MAX_VALUE),message - Example:
@Size(min = 2, max = 50) private String name;
59. @Min
- Field value must be greater than or equal to the specified minimum
- Parameters:
value(minimum — required),message - Example:
@Min(18) private int age;
60. @Max
- Field value must be less than or equal to the specified maximum
- Parameters:
value(maximum — required),message - Example:
@Max(100) private int score;
61. @Email
- Field must be a valid email address format
- Parameters:
message,regexp(custom email regex),flags - Example:
@Email private String email;
62. @Positive
- Numeric field must be strictly greater than zero
- Parameters:
message,groups - Example:
@Positive private int quantity;
63. @PositiveOrZero
- Numeric field must be zero or greater
- Parameters:
message,groups - Example:
@PositiveOrZero private int stock;
64. @Negative
- Numeric field must be strictly less than zero
- Parameters:
message,groups - Example:
@Negative private int temperature;
65. @NegativeOrZero
- Numeric field must be zero or less
- Parameters:
message,groups - Example:
@NegativeOrZero private int balance;
66. @Past
- Date/time must be in the past (strictly before now)
- Parameters:
message,groups - Example:
@Past private LocalDate birthDate;
67. @PastOrPresent
- Date/time must be in the past or exactly now
- Parameters:
message,groups - Example:
@PastOrPresent private LocalDate joinDate;
68. @Future
- Date/time must be strictly in the future
- Parameters:
message,groups - Example:
@Future private LocalDate expiryDate;
69. @FutureOrPresent
- Date/time must be now or in the future
- Parameters:
message,groups - Example:
@FutureOrPresent private LocalDate scheduledDate;
70. @Digits
- Numeric field must have at most the specified integer and fraction digits
- Parameters:
integer(max integer digits — required),fraction(max fraction digits — required),message - Example:
@Digits(integer = 6, fraction = 2) private BigDecimal price;
71. @DecimalMin
- Field value must be greater than or equal to the given decimal string
- Parameters:
value(decimal string — required),inclusive(default: true),message - Example:
@DecimalMin("0.1") private BigDecimal rate;
72. @DecimalMax
- Field value must be less than or equal to the given decimal string
- Parameters:
value(decimal string — required),inclusive(default: true),message - Example:
@DecimalMax("999.99") private BigDecimal price;
73. @AssertTrue
- Boolean field must be true
- Parameters:
message,groups - Example:
@AssertTrue private boolean termsAccepted;
74. @AssertFalse
- Boolean field must be false
- Parameters:
message,groups - Example:
@AssertFalse private boolean deleted;
75. @Constraint
- Meta-annotation used to create custom validation annotations
- Parameters:
validatedBy(validator class — required) - Example:
@Constraint(validatedBy = PhoneValidator.class) public @interface ValidPhone {}
Topic 10: Exception Handling
76. @ExceptionHandler
- Handles specific exceptions thrown within a controller or globally
- Parameters:
value(exception class(es) to handle — required) - Example:
@ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<?> handle(...)
77. @RestControllerAdvice
- Global exception handler for all REST controllers; combines
@ControllerAdvice+@ResponseBody - Parameters:
basePackages,assignableTypes,annotations - Example:
@RestControllerAdvice public class GlobalExceptionHandler {}
78. @ResponseStatus
- Sets the HTTP status code returned by a handler method or exception class
- Parameters:
value/code(HttpStatus — required),reason(message) - Example:
@ResponseStatus(HttpStatus.NOT_FOUND)