0% found this document useful (0 votes)
7 views49 pages

Essential Spring Boot Annotations Guide

This document provides a comprehensive guide to essential annotations in Spring Boot, focusing on their functionalities and usage. Key annotations such as @SpringBootApplication, @Configuration, and @EnableAutoConfiguration are discussed, highlighting their roles in simplifying Java application development. Practical examples are included to illustrate the application of these annotations in real-world scenarios.

Uploaded by

nakawi9447
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views49 pages

Essential Spring Boot Annotations Guide

This document provides a comprehensive guide to essential annotations in Spring Boot, focusing on their functionalities and usage. Key annotations such as @SpringBootApplication, @Configuration, and @EnableAutoConfiguration are discussed, highlighting their roles in simplifying Java application development. Practical examples are included to illustrate the application of these annotations in real-world scenarios.

Uploaded by

nakawi9447
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

🔹 1.

Introduction

 Spring Boot has emerged as a leading framework for the rapid development of
production-ready Java applications. Its philosophy of convention over configuration
significantly reduces the boilerplate code typically associated with enterprise Java
development, allowing developers to focus on the core business logic. A central aspect
of Spring Boot's approach to simplifying development is the extensive use of
annotations. These annotations serve as a form of metadata that provides instructions
to the Spring framework, enabling declarative programming and streamlining various
aspects of application configuration and management. This report aims to provide a
comprehensive guide to the essential annotations commonly employed in Spring Boot
applications, categorizing them based on their primary functionalities. Understanding
these annotations is crucial for developers seeking to leverage the full potential of the
Spring Boot framework and build efficient, maintainable, and robust applications. The
inclusion of practical examples will further clarify their usage.
 ---------------------------------------------------------------------------------------------------------------------
-----

🔹 2. Core Spring Boot Annotations

 2.1. @SpringBootApplication

🔹 The @SpringBootApplication annotation is a pivotal element in any Spring Boot project,


acting as a convenient entry point and encompassing several core functionalities It is a
composite annotation that bundles the features of three other essential Spring Boot
annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan.1 Typically
placed on the main application class, it streamlines the initial setup of a Spring Boot
application.1

 The @Configuration aspect signifies that the class can declare one or more beans, which
are managed by the Spring container.1 This annotation marks the class as a source of
bean definitions, offering a Java-based alternative to traditional XML configuration.2
 @EnableAutoConfiguration plays a critical role in automating the setup by instructing
Spring Boot to inspect the project's classpath and automatically configure the
application based on the dependencies added.1
 @ComponentScan is responsible for directing Spring to the packages that should be
scanned to discover components (beans) that need to be managed by the Spring
container.1
 By consolidating these three vital functionalities, @SpringBootApplication provides a
streamlined approach to bootstrapping a Spring Boot application with a single
annotation.2

🔹 Example:
🔹 Java

 package [Link];
 import [Link];
 import [Link];
 @SpringBootApplication // Combines @Configuration, @EnableAutoConfiguration,
@ComponentScan
 public class MyApplication {
 public static void main(String[] args) {
 [Link]([Link], args);
 }
 }
 // By default, scans components in [Link] and its sub-packages.

🔹 2.2. @Configuration

 The @Configuration annotation, a core element in Spring Boot, is a class-level


annotation that indicates that a class serves as a source of bean definitions for the
application context.1 Classes annotated with @Configuration typically contain methods
annotated with @Bean, which are responsible for instantiating, configuring, and
managing objects (beans) that will be used throughout the application.1 This annotation
signifies a shift from XML-based bean definitions to a code-centric approach, offering
benefits such as type safety and improved maintainability.2

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 @Configuration // Marks this class as a source of bean definitions
 public class AppConfig {
 @Bean // Declares a bean named 'emailService'
 public EmailService emailService() {
 return new EmailService(); // Instantiate and configure the bean
 }
 @Bean("notificationService") // Declares a bean with a custom name
 public SMSService smsService() {
 return new SMSService();
 }
 }
 2.3. @EnableAutoConfiguration
 @EnableAutoConfiguration is instrumental in automating the configuration of a Spring
Boot application.1 This annotation instructs Spring Boot to examine the project's
classpath and automatically configure the Spring application context based on the
dependencies found.1 For instance, if spring-boot-starter-web is present, Spring Boot
automatically configures an embedded web server and Spring MVC. This intelligent
automation embodies Spring Boot's principle of convention over configuration.2
@EnableAutoConfiguration is implicitly included when using @SpringBootApplication.1

🔹 Example (Standalone usage - less common now):

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Configuration

 @EnableAutoConfiguration // Enables auto-configuration based on classpath


dependencies
 @ComponentScan // Needed separately if not using @SpringBootApplication
 public class ManualConfiguration {
 // Can contain @Bean definitions or be empty if relying solely on auto-configuration
 }
 2.4. @ComponentScan
 The @ComponentScan annotation is used to specify the packages that Spring should
scan to discover Spring-managed components (classes annotated with @Component,
@Service, @Repository, @Controller, @RestController, @Configuration).2 When these
annotations are detected, Spring automatically creates instances (beans) and registers
them. By default, @ComponentScan is included within @SpringBootApplication and
scans the package of the main application class and its sub-packages.1

🔹 Example (Customizing scan packages):

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 @SpringBootApplication // Includes default ComponentScan
 @ComponentScan(basePackages = {"[Link]",
"[Link]", "[Link]"})
 // Overrides default scan to include specific packages, including external ones
 public class MyApplicationWithCustomScan {
 public static void main(String[] args) {
 [Link]([Link], args);
 }
 }
 2.5. @SpringBootConfiguration
 @SpringBootConfiguration is a class-level annotation indicating that a class provides
application configuration.2 It's essentially an alias for @Configuration but with specific
semantics allowing configuration to be automatically located, especially useful in testing
scenarios.7 Most applications use @SpringBootApplication, which includes this
implicitly.7

🔹 Example (Mainly for testing or specific scenarios):

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 @SpringBootConfiguration // Alias for @Configuration, helps with auto-detection in
tests
 public class CustomAppConfiguration {

🔹 @Bean

 public MyService myService() {


 return new MyServiceImpl();
 }
 }

🔹 3. Bean Management Annotations

🔹 3.1. @Bean

 The @Bean annotation is a method-level annotation typically used within


@Configuration classes to declare beans.1 The return value of the @Bean-annotated
method is registered as a bean in the Spring container.1 Spring manages its lifecycle.2
Dependencies can be injected via method parameters.2

🔹 Example (within a @Configuration class):


🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Configuration

 public class DataSourceConfig {


 // Injecting another bean (DataSourceProperties) as a dependency

🔹 @Bean

 public DataSource customDataSource(DataSourceProperties props) {


 HikariDataSource dataSource = new HikariDataSource();
 [Link]([Link]());
 [Link]([Link]());
 [Link]([Link]());
 [Link]([Link]());
 return dataSource;
 }

🔹 @Bean

 public DataSourceProperties dataSourceProperties() {


 // Assume DataSourceProperties reads from [Link]
 return new DataSourceProperties();
 }
 }

🔹 3.2. @Component

 @Component is a class-level annotation marking a class as a Spring-managed


component.2 It's a generic stereotype for auto-detection via @ComponentScan.2 Spring
creates an instance (bean) and registers it.2

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 @Component // Marks this class as a generic Spring component
 public class DataFormatter {
 public String format(Object data) {
 // Formatting logic...
 return [Link]();
 }
 }

🔹 3.3. @Service

 The @Service annotation is a specialization of @Component used to denote classes in


the service layer, holding business logic.2 It provides semantic clarity and enables auto-
detection.2

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 @Service // Marks this class as a service component
 public class UserService {
 private final UserRepository userRepository;
 @Autowired // Constructor injection
 public UserService(UserRepository userRepository) {
 [Link] = userRepository;
 }
 public User findUserById(Long id) {
 return [Link](id).orElse(null);
 }
 // Other business logic methods...
 }

🔹 3.4. @Repository

 @Repository is another specialization of @Component, used for classes in the data


access layer.2 It clearly indicates data access responsibility and enables Spring's
exception translation mechanism.2

🔹 Example (Often used on interfaces with Spring Data JPA):


🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link]; // Optional with Spring Data JPA,
but good practice
 @Repository // Marks this interface/class as a data access component and enables
exception translation
 public interface UserRepository extends JpaRepository<User, Long> {
 // Spring Data JPA automatically implements basic CRUD methods
 // Can add custom query methods here
 User findByUsername(String username);
 }

🔹 Example (Manual implementation):

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 @Repository // Marks this class as a data access component and enables exception
translation
 public class ProductRepositoryImpl implements ProductRepository {
 private final JdbcTemplate jdbcTemplate;
 public ProductRepositoryImpl(DataSource dataSource) {
 [Link] = new JdbcTemplate(dataSource);
 }

🔹 @Override

 public Product findById(Long id) {


 // JDBC logic to find product...
 // Exceptions will be translated to Spring's DataAccessException hierarchy
 return null; // Placeholder
 }
 }

🔹 3.5. @Autowired
 The @Autowired annotation enables automatic dependency injection.1 Spring finds a
matching bean in the context and injects it into fields, constructors, or setter methods.1
Constructor injection is generally preferred.2

🔹 Example (Field, Constructor, Setter):

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Controller

 public class UserController {


 // 1. Field Injection (Simpler, but less recommended for required dependencies)

🔹 @Autowired

 private DataFormatter dataFormatter;


 private final UserService userService;
 private NotificationService notificationService; // Optional dependency
 // 2. Constructor Injection (Recommended for required dependencies)
 @Autowired // @Autowired is optional on constructors if only one exists since Spring
4.3
 public UserController(UserService userService) {
 [Link] = userService;
 }
 // 3. Setter Injection (Useful for optional dependencies)

🔹 @Autowired

 public void setNotificationService(NotificationService notificationService) {


 [Link] = notificationService;
 }
 // ... controller methods using userService, dataFormatter, notificationService
 }

🔹 3.6. @Qualifier
 The @Qualifier annotation is used with @Autowired to specify which bean to inject
when multiple candidates of the same type exist.2 It references the bean's unique
identifier (default name or custom name).15

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Configuration

 public class NotificationConfig {


 @Bean("emailSender") // Bean named "emailSender"
 public NotificationSender emailNotificationSender() {
 return new EmailNotificationSender();
 }
 @Bean("smsSender") // Bean named "smsSender"
 public NotificationSender smsNotificationSender() {
 return new SmsNotificationSender();
 }
 }

🔹 // --- Usage ---

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Service

 public class OrderService {


 private final NotificationSender notificationSender;

🔹 @Autowired
 public OrderService(@Qualifier("emailSender") NotificationSender notificationSender)
{ // Specify "emailSender" bean
 [Link] = notificationSender;
 }
 public void placeOrder() {
 // ... logic
 [Link]("Order placed successfully!");
 }
 }

🔹 3.7. @Primary

 The @Primary annotation indicates the preferred bean when multiple candidates of the
same type exist for autowiring, unless explicitly specified otherwise with @Qualifier.9,
15

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Configuration

 public class NotificationConfig {


 @Bean("emailSender")
 @Primary // Email is the default notification method
 public NotificationSender emailNotificationSender() {
 return new EmailNotificationSender();
 }
 @Bean("smsSender")
 public NotificationSender smsNotificationSender() {
 return new SmsNotificationSender();
 }
 }

🔹 // --- Usage ---


 package [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Service

 public class CustomerService {


 // No @Qualifier needed; @Primary bean (EmailNotificationSender) will be injected

🔹 @Autowired

 private NotificationSender notificationSender;


 public void registerCustomer() {
 // ... logic
 [Link]("Welcome!"); // Sends via email by default
 }
 }

🔹 3.8. @Lazy

 The @Lazy annotation delays the initialization of a bean until it's first requested,
overriding the default eager initialization of singletons.8, 15 This can improve startup
time or help resolve circular dependencies.15

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Service

 @Lazy // This bean will only be created when first injected or requested
 public class HeavyResourceService {
 public HeavyResourceService() {

🔹 [Link]("HeavyResourceService: Constructor called - Initializing...");

 // Simulate heavy initialization


 try { [Link](2000); } catch (InterruptedException e) { /* ignore */ }
 }
 @PostConstruct
 public void init() {

🔹 [Link]("HeavyResourceService: PostConstruct finished.");

 }
 public void performAction() {

🔹 [Link]("HeavyResourceService: Action performed.");

 }
 }

🔹 // --- Usage ---

 // When ApplicationRunner runs, HeavyResourceService constructor won't be called


 // immediately unless another eager bean depends on it. It will be called
 // when [Link]() is invoked if not already created.
 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Component

 public class AppRunner implements ApplicationRunner {

🔹 @Autowired

 private HeavyResourceService heavyResourceService; // Injection triggers lazy init if


needed

🔹 @Override

 public void run(ApplicationArguments args) throws Exception {

🔹 [Link]("ApplicationRunner: Starting...");

 // Uncommenting the line below would trigger the lazy initialization


 // [Link]();

🔹 [Link]("ApplicationRunner: Finished.");
 }
 }
 4. REST API Development Annotations
 4.1. @RestController
 @RestController is a convenience annotation combining @Controller and
@ResponseBody.1 It marks a class as a controller where handler methods return
domain objects directly converted to the response body (usually JSON/XML), suitable for
REST APIs.2

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link].*;
 import [Link];
 @RestController // Combines @Controller and @ResponseBody for all methods
 @RequestMapping("/api/products") // Base path for all methods in this controller
 public class ProductRestController {

🔹 @Autowired

 private ProductService productService;


 @GetMapping("/{id}")
 public Product getProductById(@PathVariable Long id) {
 return [Link](id); // Return object directly serialized to response body
 }
 @GetMapping
 public List<Product> getAllProducts() {
 return [Link](); // Return list directly serialized
 }
 @PostMapping
 public Product createProduct(@RequestBody Product product) {
 return [Link](product); // Return created object
 }
 }

🔹 4.2. @Controller
 The @Controller annotation marks a class as a Spring MVC controller for handling web
requests.2 Unlike @RestController, it's typically used in traditional web apps where
methods return view names (e.g., for Thymeleaf, JSP) rather than directly writing to the
response body.6

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 @Controller // Standard MVC Controller
 @RequestMapping("/products")
 public class ProductWebController {

🔹 @Autowired

 private ProductService productService;


 @GetMapping("/list")
 public String showProductList(Model model) {
 [Link]("products", [Link]());
 return "product-list"; // Returns the logical view name (e.g., [Link])
 }
 }
 4.3. @RequestMapping
 @RequestMapping maps HTTP requests to handler methods.1 It can be applied at class
level (base path) and method level (specific path).19 It handles various HTTP
methods.19

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link].*;
 @RestController

🔹 @RequestMapping("/api/items") // Class-level mapping: all requests start with /api/items


 public class ItemController {
 // Maps GET requests to /api/items/{id}
 @RequestMapping(value = "/{id}", method = [Link])
 public ResponseEntity<String> getItem(@PathVariable String id) {

🔹 return [Link]("Item details for ID: " + id);

 }
 // Maps POST requests to /api/items
 @RequestMapping(method = [Link])
 public ResponseEntity<String> createItem(@RequestBody String itemData) {

🔹 return [Link]("Item created with data: " + itemData);

 }
 }
 4.4. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping
 These are shortcuts for @RequestMapping specific to HTTP methods (GET, POST, PUT,
DELETE, PATCH).1 They improve readability.20

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link].*;
 @RestController
 @RequestMapping("/api/users")
 public class UserShortcutController {
 @GetMapping("/{id}") // Shortcut for [Link]
 public User getUser(@PathVariable Long id) {
 // ... find user by id
 return new User(id, "Example User"); // Placeholder
 }
 @PostMapping // Shortcut for [Link]
 public ResponseEntity<User> createUser(@RequestBody User user) {
 // ... save user
 return [Link](201).body(user);
 }
 @PutMapping("/{id}") // Shortcut for [Link]
 public User updateUser(@PathVariable Long id, @RequestBody User user) {
 // ... update user by id
 [Link](id); // Ensure ID matches path
 return user;
 }
 @DeleteMapping("/{id}") // Shortcut for [Link]
 public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
 // ... delete user by id
 return [Link]().build();
 }
 @PatchMapping("/{id}") // Shortcut for [Link]
 public User partiallyUpdateUser(@PathVariable Long id, @RequestBody
[Link]<String, Object> updates) {
 // ... apply partial updates to user by id
 return new User(id, "Partially Updated User"); // Placeholder
 }
 }
 // Dummy User class for example
 class User {
 private Long id;
 private String name;
 public User(Long id, String name) { [Link] = id; [Link] = name; }
 public Long getId() { return id; }
 public void setId(Long id) { [Link] = id; }
 public String getName() { return name; }
 public void setName(String name) { [Link] = name; }
 }
 4.5. @PathVariable
 The @PathVariable annotation extracts values from URI template variables
(placeholders like {id}) and binds them to method parameters.1, 2

🔹 Example:

🔹 Java

 package [Link];
 import [Link].*;
 @RestController
 @RequestMapping("/api/orders")
 public class OrderController {
 // Extracts 'orderId' from the path /api/orders/{orderId}
 @GetMapping("/{orderId}")
 public String getOrderDetails(@PathVariable Long orderId) {
🔹 return "Details for Order ID: " + orderId;

 }
 // Extracts 'customerId' and 'orderId' from
/api/customers/{customerId}/orders/{orderId}
 @GetMapping("/customers/{customerId}/orders/{orderId}")
 public String getCustomerOrder(
 @PathVariable("customerId") String custId, // Can specify name if different from param
 @PathVariable Long orderId) {

🔹 return "Details for Order ID: " + orderId + " for Customer: " + custId;

 }
 }
 4.6. @RequestParam
 The @RequestParam annotation extracts query parameters (e.g., ?name=value) from
the request URL and binds them to method parameters.2 It supports required/optional
status and default values.6

🔹 Example:

🔹 Java

 package [Link];
 import [Link].*;
 import [Link];
 import [Link];
 @RestController
 @RequestMapping("/api/search")
 public class SearchController {
 // Handles requests like /api/search/products?query=laptop
 @GetMapping("/products")
 public String searchProducts(
 @RequestParam String query, // Required parameter
 @RequestParam(required = false) String category, // Optional parameter
 @RequestParam(defaultValue = "10") int size, // Parameter with default value
 @RequestParam(name = "sort") Optional<String> sortOrder // Optional using Java 8
Optional
 ){
 StringBuilder response = new StringBuilder();
 [Link]("Searching for '").append(query).append("'");
 if (category != null) {
 [Link](" in category '").append(category).append("'");
 }

🔹 [Link](". Page size: ").append(size);

🔹 [Link](s -> [Link](". Sorting by: ").append(s));

 return [Link]();
 }
 // Handles requests like /api/search/users?role=ADMIN&role=SUPPORT
 @GetMapping("/users")
 public String searchUsersByRole(@RequestParam List<String> role) {

🔹 return "Searching for users with roles: " + [Link](", ", role);

 }
 }
 4.7. @RequestBody
 The @RequestBody annotation binds the HTTP request body content (e.g., JSON, XML)
to a method parameter.1 Spring uses HttpMessageConverters for the conversion.2
Commonly used with POST, PUT, PATCH.

🔹 Example:

🔹 Java

 package [Link];
 import [Link]; // Assume Product is a POJO
 import [Link];
 import [Link].*;
 @RestController
 @RequestMapping("/api/products")
 public class ProductApiController {
 // Binds the JSON/XML body of the POST request to the product parameter
 @PostMapping
 public ResponseEntity<Product> createProduct(@RequestBody Product product) {

🔹 [Link]("Received product: " + [Link]());

 // ... logic to save the product ...


 [Link](1L); // Simulate saving and getting an ID
 return [Link](201).body(product);
 }
 }
 4.8. @ResponseBody
 The @ResponseBody annotation indicates that a method's return value should be
bound directly to the web response body.2 Spring uses HttpMessageConverters to
serialize the object (often to JSON). It's included implicitly in methods within a
@RestController-annotated class.2

🔹 Example (Used with @Controller, not @RestController):

🔹 Java

 package [Link];
 import [Link]; // Assume a simple POJO
 import [Link];
 import [Link];
 import [Link]; // Explicitly needed
here
 @Controller // Not a @RestController
 @RequestMapping("/app-status")
 public class StatusController {
 @GetMapping("/health")
 @ResponseBody // Ensures the return value is written to the response body as
JSON/XML
 public StatusResponse getHealthStatus() {
 return new StatusResponse("OK", "Application is running");
 }
 @GetMapping("/info")
 public String getInfoPage() {
 // Without @ResponseBody, this returns a view name
 return "application-info";
 }
 }
 5. Spring Data JPA Annotations

🔹 5.1. @Entity

 The @Entity annotation (from [Link]) marks a Java class as a JPA entity,
representing a row in a database table.24 Requires a primary key (@Id).27

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 @Entity // Marks this class as a JPA entity
 public class Customer {
 @Id // Marks this field as the primary key
 @GeneratedValue(strategy = [Link]) // Configures auto-generation
 private Long id;
 private String firstName;
 private String lastName;

🔹 // Constructors, Getters, Setters...

 }

🔹 5.2. @Table

 The @Table annotation specifies details of the database table mapped to the entity, like
table name, schema, and unique constraints.24

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Entity

 @Table(name = "app_customers", schema = "public", // Specify table name and schema


 uniqueConstraints = @UniqueConstraint(columnNames = {"email"})) // Define a unique
constraint
 public class Customer {

🔹 @Id

 private Long id;


 private String email;
 // Other fields, constructors, getters, setters...
 }

🔹 5.3. @Id
 The @Id annotation marks a field as the primary key for the entity.24 Essential for JPA
entity management.27
 Example (See @Entity example above)
 5.4. @GeneratedValue
 The @GeneratedValue annotation specifies how the primary key value is automatically
generated.24 Common strategies include IDENTITY (database auto-increment),
SEQUENCE (database sequence), AUTO (provider choice).27
 Example (See @Entity example above)

🔹 5.5. @Column

 The @Column annotation defines attributes for the database column mapped to an
entity field, such as name, length, nullability, uniqueness, and column definition.24

🔹 Example:

🔹 Java

 package [Link];
 import [Link].*;
 import [Link];

🔹 @Entity

 @Table(name = "products")
 public class Product {

🔹 @Id

 @GeneratedValue(strategy = [Link])
 private Long id;
 @Column(name = "product_name", length = 100, nullable = false) // Custom column
name, length, not nullable
 private String name;
 @Column(unique = true) // Ensures this column value is unique in the table
 private String sku;
 @Column(columnDefinition = "TEXT") // Specify custom SQL type (database-dependent)
 private String description;
 @Column(updatable = false) // This column won't be included in SQL UPDATE
statements
 private LocalDate createdDate;

🔹 // Constructors, Getters, Setters...


 }
 5.6. Relationship Annotations (@ManyToOne, @OneToMany, @ManyToMany,
@OneToOne)
 These annotations define relationships between entities.

🔹 @ManyToOne: Many instances of the current entity relate to one instance of another entity
(e.g., many Orders belong to one Customer). Often uses @JoinColumn for the foreign key.32,
47

🔹 @OneToMany: One instance of the current entity relates to many instances of another (e.g.,
one Customer has many Orders). Often uses mappedBy in bidirectional relationships.48, 49

🔹 @ManyToMany: Many instances relate to many others (e.g., many Students enroll in many
Courses). Typically uses @JoinTable.32

🔹 @OneToOne: One instance relates to exactly one other (e.g., one User has one UserProfile).
Can use @JoinColumn or shared primary key.33

🔹 Example:

🔹 Java

 package [Link];
 import [Link].*;
 import [Link];
 import [Link];

🔹 // --- Customer Entity ---

🔹 @Entity

 public class Customer {


 @Id @GeneratedValue private Long id;
 private String name;
 // One Customer can have Many Orders
 // 'mappedBy="customer"' indicates that the 'customer' field in the Order entity owns
the relationship
 @OneToMany(mappedBy = "customer", cascade = [Link], fetch =
[Link])
 private List<Order> orders;

🔹 // Getters, Setters...

 }
🔹 // --- Order Entity ---

🔹 @Entity

 @Table(name = "customer_orders")
 public class Order {
 @Id @GeneratedValue private Long id;
 private [Link] orderDate;
 // Many Orders belong to One Customer
 @ManyToOne(fetch = [Link]) // LAZY is often preferred for performance
 @JoinColumn(name = "customer_id", nullable = false) // Defines the foreign key column
 private Customer customer;

🔹 // Getters, Setters...

 }

🔹 // --- Student Entity ---

🔹 @Entity

 public class Student {


 @Id @GeneratedValue private Long id;
 private String name;
 @ManyToMany(cascade = { [Link], [Link] })
 @JoinTable(name = "student_course", // Defines the join table
 joinColumns = @JoinColumn(name = "student_id"), // FK column for Student
 inverseJoinColumns = @JoinColumn(name = "course_id")) // FK column for Course
 private Set<Course> courses;

🔹 // Getters, Setters...

 }

🔹 // --- Course Entity ---

🔹 @Entity

 public class Course {


 @Id @GeneratedValue private Long id;
 private String title;
 // 'mappedBy="courses"' points to the field in Student that owns the relationship
 @ManyToMany(mappedBy = "courses")
 private Set<Student> students;
🔹 // Getters, Setters...

 }

🔹 // --- User Entity ---

🔹 @Entity

 public class User {


 @Id @GeneratedValue private Long id;
 private String username;
 // One User has One UserProfile
 // Cascade ensures profile is saved/deleted with user. 'mappedBy' indicates UserProfile
owns it.
 @OneToOne(mappedBy = "user", cascade = [Link], fetch = [Link],
optional = false)
 private UserProfile userProfile;

🔹 // Getters, Setters...

 }
 // --- UserProfile Entity ---

🔹 @Entity

 public class UserProfile {


 @Id @GeneratedValue private Long id;
 private String bio;
 // One UserProfile belongs to One User
 @OneToOne(fetch = [Link])
 @JoinColumn(name = "user_id", nullable = false) // Foreign key column in UserProfile
table
 private User user;

🔹 // Getters, Setters...

 }
 5.7. @ElementCollection
 Defines a one-to-many relationship to a collection of non-entity types (Embeddables or
basic types like String).34 Stores values in a separate collection table defined by
@CollectionTable.38, 50

🔹 Example:
🔹 Java

 package [Link];
 import [Link].*;
 import [Link];

🔹 @Entity

 public class Employee {


 @Id @GeneratedValue private Long id;
 private String name;
 // Collection of basic type (String)
 @ElementCollection(fetch = [Link]) // EAGER or LAZY fetch
 @CollectionTable(name = "employee_nicknames", // Name of the collection table
 joinColumns = @JoinColumn(name = "employee_id")) // Foreign key back to Employee
 @Column(name = "nickname") // Name of the column storing the nickname values
 private Set<String> nicknames;
 // Collection of Embeddable type (Address)
 @ElementCollection
 @CollectionTable(name = "employee_addresses", joinColumns = @JoinColumn(name =
"employee_id"))
 private Set<Address> addresses; // Assumes Address is an @Embeddable class

🔹 // Getters, Setters...

 }
 @Embeddable // Address is not an entity, just a value object
 public class Address {
 private String street;
 private String city;
 private String zipCode;

🔹 // Getters, Setters...

 }

🔹 5.8. @Embedded

 Embeds an @Embeddable object's fields directly into the owning entity's table
columns.34 Use @AttributeOverride(s) to customize column names if needed.39

🔹 Example:

🔹 Java
 package [Link];
 import [Link].*;

🔹 @Entity

 public class Company {


 @Id @GeneratedValue private Long id;
 private String name;
 @Embedded // Embed the Address object's fields into the Company table
 private Address headquartersAddress;

🔹 @Embedded

 @AttributeOverrides({ // Customize column names for the embedded object's fields


 @AttributeOverride(name = "street", column = @Column(name = "branch_street")),
 @AttributeOverride(name = "city", column = @Column(name = "branch_city")),
 @AttributeOverride(name = "zipCode", column = @Column(name = "branch_zip"))
 })
 private Address branchAddress;

🔹 // Getters, Setters...

 }
 // Address class is the same @Embeddable class from the @ElementCollection example

🔹 5.9. @Embeddable

 Marks a class as embeddable, meaning its instances are stored as part of an owning
entity and don't have their own lifecycle or primary key.34 Used with @Embedded or
@ElementCollection.34
 Example (See Address class in @ElementCollection and @Embedded examples above)

🔹 5.10. @Query

 Defines custom JPQL or native SQL queries directly on repository methods.25, 26 Use
@Param to bind method parameters to query parameters.26

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 public interface UserRepository extends JpaRepository<User, Long> {
 // Custom JPQL query with named parameters

🔹 @Query("SELECT u FROM User u WHERE [Link] = :status AND [Link] = :city")

 List<User> findUsersByStatusAndCity(@Param("status") String status, @Param("city")


String city);
 // Custom native SQL query

🔹 @Query(value = "SELECT * FROM users WHERE email_address LIKE %:domain", nativeQuery


= true)

 List<User> findUsersByEmailDomain(@Param("domain") String domain);


 // Custom query for projection (returning specific fields) - using an interface projection

🔹 @Query("SELECT [Link] as username, [Link] as email FROM User u WHERE [Link]


= :id")

 UserSummary findUserSummaryById(@Param("id") Long id);


 // Custom query for update/delete operations (requires @Modifying and
@Transactional)

🔹 @Modifying

🔹 @Query("UPDATE User u SET [Link] = :newStatus WHERE [Link] < :date")

 int updateStatusForInactiveUsers(@Param("newStatus") String newStatus,


@Param("date") [Link] date);
 }

🔹 // --- Projection Interface ---

 package [Link];
 public interface UserSummary {
 String getUsername();
 String getEmail();
 }
 5.11. @EnableJpaRepositories
 Enables Spring Data JPA repository support, scanning specified packages for interfaces
extending JpaRepository (or other Spring Data repository interfaces) and creating
implementations.25, 26 Often implicitly enabled by Spring Boot auto-configuration
when spring-boot-starter-data-jpa is present.

🔹 Example (Explicit usage):

🔹 Java

 package [Link];
 import [Link];
 import [Link];

🔹 @Configuration

 @EnableJpaRepositories(basePackages = "[Link]") // Specify


package to scan
 public class JpaConfig {
 // Other JPA related beans like EntityManagerFactory could be defined here
 // if not using Spring Boot auto-configuration.
 }

🔹 6. Property Management Annotations

 6.1. @ConfigurationProperties
 Maps external configuration properties (from [Link]/yml) to fields of a
POJO.13 Specify a prefix to group related properties. Supports validation.13

🔹 Example:

🔹 [Link]:

🔹 Properties

🔹 [Link]=[Link]

 [Link]=YOUR_API_KEY_HERE
 [Link]-ms=5000
 [Link]=true

🔹 Java Class:

🔹 Java

 package [Link];
 import [Link];
 import [Link]; // Or use
@EnableConfigurationProperties
 import [Link];
 import [Link];
 import [Link];
 @Component // Makes it a bean eligible for property binding
 @ConfigurationProperties(prefix = "[Link]") // Binds properties starting with
"[Link]"
 @Validated // Enables validation on the fields
 public class ApiProperties {

🔹 @NotBlank // Validation: URL cannot be blank

 private String url;


 @NotBlank
 private String key;

🔹 @Positive // Validation: Timeout must be positive

 private int timeoutMs;


 // Getters and Setters...
 public String getUrl() { return url; }
 public void setUrl(String url) { [Link] = url; }
 public String getKey() { return key; }
 public void setKey(String key) { [Link] = key; }
 public int getTimeoutMs() { return timeoutMs; }
 public void setTimeoutMs(int timeoutMs) { [Link] = timeoutMs; }
 }

🔹 // Nested properties example:

🔹 @Component

 @ConfigurationProperties(prefix = "[Link]")
 public class FeatureFlags {
 private NewUI newUi = new NewUI(); // Nested object
 public NewUI getNewUi() { return newUi; }
 public void setNewUi(NewUI newUi) { [Link] = newUi; }
 public static class NewUI { // Nested static class for properties
 private boolean enabled;
 public boolean isEnabled() { return enabled; }
 public void setEnabled(boolean enabled) { [Link] = enabled; }
 }
 }
🔹 // --- Usage ---

 package [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Service

 public class ExternalApiService {


 private final ApiProperties apiProperties;

🔹 @Autowired

 public ExternalApiService(ApiProperties apiProperties) {


 [Link] = apiProperties;

🔹 [Link]("API URL: " + [Link]());

🔹 [Link]("API Timeout: " + [Link]());

 }
 // ... use properties
 }

🔹 // Note: Ensure you have a dependency like 'spring-boot-starter-validation' for @Validated


to work.

 // Alternatively, enable via @EnableConfigurationProperties([Link]) on a


@Configuration class.
 6.2. @PropertySource
 Loads properties from additional specified file locations into the Spring Environment.23
Properties loaded this way usually have higher precedence than defaults.23

🔹 Example:

🔹 [Link]:

🔹 Properties

🔹 [Link]=[Link]

 [Link]=Hello from custom properties!

🔹 Java Configuration Class:


🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Configuration

🔹 @PropertySource("classpath:[Link]") // Load properties from this file

🔹 // Can specify multiple sources: @PropertySource({"classpath:...", "file:/..."})

 public class CustomPropertiesConfig {


 @Value("${[Link]}") // Inject value from the custom file
 private String customMessage;
 @PostConstruct
 public void printMessage() {

🔹 [Link]("Custom message loaded: " + customMessage);

 }
 }

🔹 6.3. @Value

 Injects individual values from property sources (like [Link], environment


variables, @PropertySource files) into fields.2 Supports Spring Expression Language
(SpEL) and default values.23

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];

🔹 @Component

 public class AppInfoComponent {


 // Inject from [Link] or system property
 @Value("${[Link]}")
 private String applicationName;
 // Inject with a default value if property '[Link]' is not found

🔹 @Value("${[Link].0.0}")

 private String applicationVersion;


 // Inject system property '[Link]'
 @Value("${[Link]}")
 private String javaHome;
 // Inject value from another bean using SpEL
 @Value("#{[Link]}") // Assumes a bean named
'dataSourceProperties' exists
 private String databaseUrl;
 // Inject a static value or result of SpEL expression
 @Value("#{'Default User'.toUpperCase()}")
 private String defaultUser;
 // Getters or methods using these values...
 public void displayInfo() {

🔹 [Link]("App Name: " + applicationName);

🔹 [Link]("App Version: " + applicationVersion);

🔹 [Link]("Java Home: " + javaHome);

🔹 [Link]("DB URL: " + databaseUrl);

🔹 [Link]("Default User (processed): " + defaultUser);

 }
 }

🔹 7. Testing Annotations

 7.1. @SpringBootTest
 Loads the full Spring ApplicationContext for integration tests, closely mimicking the
production environment.28 The webEnvironment attribute controls web server setup
(e.g., MOCK, RANDOM_PORT).30, 63

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import static [Link];
 // Loads the full application context
 @SpringBootTest(webEnvironment = [Link]) // or
RANDOM_PORT, NONE etc.
 class MyApplicationIntegrationTest {
 @Autowired // Inject real beans from the context
 private UserService userService;

🔹 @Autowired

 private ApplicationContext context;

🔹 @Test

 void contextLoads() {
 assertThat(context).isNotNull();
 }

🔹 @Test

 void userServiceShouldBeAvailable() {
 assertThat(userService).isNotNull();
 // Perform tests using the actual service bean
 }
 }
 7.2. @WebMvcTest
 Tests the Spring MVC web layer (controllers) in isolation.30 Instantiates only web-
related beans (controllers, filters, MVC infrastructure) and auto-configures MockMvc.30
Excludes service, repository, component beans unless explicitly included or mocked.30

🔹 Example:

🔹 Java

 package [Link];
 import [Link]; // Service dependency of the
controller
 import [Link];
 import [Link];
 import [Link];
 import [Link]; // To mock
dependencies
 import [Link];
 import static [Link];
 import static
[Link];
 import static
[Link];
 import static
[Link];
 // Test only ProductRestController, providing mocks for its dependencies
 @WebMvcTest([Link])
 class ProductRestControllerTest {

🔹 @Autowired

 private MockMvc mockMvc; // Auto-configured MockMvc for sending requests


 @MockBean // Creates a Mockito mock for ProductService and adds it to the context
 private ProductService productService;

🔹 @Test

 void getProductByIdShouldReturnProduct() throws Exception {

🔹 // Given: Define mock behavior

 long productId = 1L;


 Product mockProduct = new Product(productId, "Test Product", 99.99);
 given([Link](productId)).willReturn(mockProduct);

🔹 // When & Then: Perform request and assert response

 [Link](get("/api/products/{id}", productId))
 .andExpect(status().isOk())

🔹 .andExpect(content().json("{\"id\":1,\"name\":\"Test Product\",\"price\":99.99}")); //
Assuming Product serializes like this

 }
 }
 // Dummy Product class for example
 class Product {
 private Long id; private String name; private double price;
 public Product(Long id, String name, double price) { [Link] = id; [Link] = name;
[Link] = price;}
 // Getters needed for JSON serialization
 public Long getId() { return id; } public String getName() { return name; } public double
getPrice() { return price; }
 }
 7.3. @DataJpaTest
 Tests the persistence layer (JPA repositories) specifically.28 Configures an in-memory
database, JPA entities, and Spring Data repositories.28 Tests are transactional and rolled
back by default.28 Auto-configures TestEntityManager.28

🔹 Example:

🔹 Java

 package [Link];
 import [Link]; // The @Entity class
 import [Link];
 import [Link];
 import [Link];
 import [Link]; // For
setting up data
 import static [Link];
 @DataJpaTest // Configures in-memory DB, scans for @Entity, configures repositories
 // By default, replaces real DB config with an embedded one (like H2)
 class UserRepositoryTest {

🔹 @Autowired

 private TestEntityManager entityManager; // Helper to persist/find entities in tests

🔹 @Autowired

 private UserRepository userRepository; // The repository interface under test

🔹 @Test

 void findByUsernameShouldReturnUser() {

🔹 // Given: Setup data using TestEntityManager

 User user = new User();


 [Link]("testuser");
 [Link]("test@[Link]");
 [Link](user); // Persist the entity
 [Link](); // Ensure data is written to DB
🔹 // When: Call the repository method

 User foundUser = [Link]("testuser");

🔹 // Then: Assert the result

 assertThat(foundUser).isNotNull();
 assertThat([Link]()).isEqualTo("testuser");
 }

🔹 @Test

 void saveShouldPersistUser() {

🔹 // Given

 User newUser = new User();


 [Link]("newbie");
 [Link]("new@[Link]");

🔹 // When

 User savedUser = [Link](newUser);

🔹 // Then

 assertThat(savedUser).isNotNull();
 assertThat([Link]()).isNotNull(); // Should have an ID assigned
 User retrievedUser = [Link]([Link], [Link]());
 assertThat([Link]()).isEqualTo("newbie");
 }
 }
 // Dummy User entity for example
 @[Link] @[Link](name="users")
 class User {
 @[Link] @[Link] private Long id;
 private String username; private String email;

🔹 // Getters & Setters...

 public Long getId() { return id;} public String getUsername() { return username;} public
void setUsername(String u) {[Link]=u;}
 public String getEmail() { return email; } public void setEmail(String e) {[Link]=e;}
 }
 7.4. @TestConfiguration
 Defines extra beans or customizes configuration specifically for tests, often used within
a test class as a static inner class or imported via @Import.31 Avoids loading the full
application configuration.31

🔹 Example:

🔹 Java

 package [Link];
 import [Link]; // Assume this has real config
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link]; // To override real bean
 import [Link];

🔹 // --- The Service Under Test ---

 @[Link]
 class MyProcessingService {
 private final ExternalServiceClient externalServiceClient;
 public MyProcessingService(ExternalServiceClient client) { [Link] =
client;}

🔹 public String process() { return "Processed with: " + [Link](); }

 }

🔹 // --- Dummy External Service Client ---

 interface ExternalServiceClient { String getData(); }


 class RealExternalServiceClient implements ExternalServiceClient { public String
getData() { return "REAL_DATA"; }}
 class MockExternalServiceClient implements ExternalServiceClient { public String
getData() { return "MOCK_TEST_DATA"; }}

🔹 // --- The Test ---

 @SpringBootTest // Might load broader context


 @Import([Link]) // Import the test configuration
 class MyProcessingServiceTest {
 // Define test-specific beans here
 @TestConfiguration // Can be static inner class or separate class
 static class Config {

🔹 @Bean

 @Primary // Make this the primary bean, overriding any real one
 public ExternalServiceClient testExternalServiceClient() {
 [Link]("Creating MOCK ExternalServiceClient for test!");
 return new MockExternalServiceClient(); // Provide a mock or stub implementation
 }
 }

🔹 @Autowired

 private MyProcessingService myProcessingService;


 @Autowired // Can inject the test bean too
 private ExternalServiceClient externalServiceClient;

🔹 @Test

 void serviceShouldUseTestBean() {
 String result = [Link]();
 [Link](result)

🔹 .isEqualTo("Processed with: MOCK_TEST_DATA");

 // Verify the injected client is the mock one


 [Link](externalServiceClient)
 .isInstanceOf([Link]);
 }
 }
 7.5. @MockBean
 Adds Mockito mocks to the Spring ApplicationContext.30 Replaces any existing bean of
the same type with the mock or adds the mock if no bean exists.31 Essential for isolating
components under test.31
 Example (See @WebMvcTest example where ProductService is mocked using
@MockBean)
 7.6. @TestPropertySource
 Configures property file locations or inlined properties specifically for a test class.31
Properties defined here override those from [Link] or other sources.60

🔹 Example:

🔹 Java
 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import static [Link];
 // --- Component using properties ---

🔹 @Component

 class PropertyReaderComponent {
 @Value("${[Link]}") private boolean featureXEnabled;
 @Value("${[Link]}") private String serviceUrl;

🔹 @Value("${message:default message}") private String message;

 public boolean isFeatureXEnabled() { return featureXEnabled; }


 public String getServiceUrl() { return serviceUrl; }
 public String getMessage() { return message; }
 }

🔹 // --- The Test ---

 @SpringBootTest
 // Load properties from a test file AND override specific properties inline

🔹 @TestPropertySource(locations = "classpath:[Link]",

 properties = { "[Link]=false", "message=Inline test message" })


 class PropertyReaderComponentTest {

🔹 @Autowired

 private PropertyReaderComponent propertyReader;

🔹 @Test

 void propertiesShouldBeOverridden() {
 // Value from inline property override
 assertThat([Link]()).isFalse();

🔹 // Value from [Link] (assume it has [Link]=[Link]


🔹 assertThat([Link]()).isEqualTo("[Link]

 // Value from inline property override (higher precedence than test file or default)
 assertThat([Link]()).isEqualTo("Inline test message");
 }
 }
 // --- [Link] (in src/test/resources) ---

🔹 // [Link]=[Link]

 // [Link]=true <- This will be overridden by the inline property in the test

🔹 8. Spring Security Annotations

 8.1. @EnableMethodSecurity
 Enables method-level security using annotations like @PreAuthorize, @PostAuthorize,
@Secured, @RolesAllowed.65, 66 Replaces the older @EnableGlobalMethodSecurity.
Uses AuthorizationManager.66

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import
[Link]
curity;
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];

🔹 @Configuration

 @EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true) // Enable


@Secured and @RolesAllowed support
 public class SecurityConfig {

🔹 @Bean

 public InMemoryUserDetailsManager userDetailsService() {


 UserDetails user = [Link]()
 .username("user").password("password").roles("USER").authorities("read").build();
 UserDetails admin = [Link]()
 .username("admin").password("password").roles("ADMIN", "USER").authorities("read",
"write").build();
 return new InMemoryUserDetailsManager(user, admin);
 }

🔹 @Bean

 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {


 [Link](auth -> [Link]().authenticated())

🔹 .httpBasic(); // Example: Use HTTP Basic auth

 return [Link]();
 }
 // RoleHierarchy bean can also be defined here if needed (see @RoleHierarchy example)
 }

🔹 8.2. @Secured

 Specifies a list of role names (must start with ROLE_ by convention) allowed to access a
method.22 Does not support SpEL.22 Requires securedEnabled = true in
@EnableMethodSecurity.

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];

🔹 @Service

 public class AdminService {


 @Secured("ROLE_ADMIN") // Only users with ROLE_ADMIN can execute this
 public String performAdminTask() {
 return "Admin task performed successfully.";
 }
 @Secured({"ROLE_ADMIN", "ROLE_SUPPORT_LEVEL_2"}) // Requires either role
 public String performHighLevelSupportTask() {
 return "High-level support task done.";
 }
 }
 8.3. @PreAuthorize
 Uses Spring Expression Language (SpEL) to enforce authorization before method
execution.22 Allows complex rules based on roles, authorities, user properties, method
arguments etc.22

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];

🔹 @Service

 public class ResourceService {


 // Requires 'ADMIN' role OR 'write' authority
 @PreAuthorize("hasRole('ADMIN') or hasAuthority('write')")
 public void updateResource(String resourceId, Object data) {

🔹 [Link]("Updating resource: " + resourceId);

 }
 // Access based on username matching the method argument 'ownerUsername'
 @PreAuthorize("#ownerUsername == [Link]")
 public String getResourceForOwner(String resourceId, String ownerUsername) {
 return "Resource " + resourceId + " data for " + ownerUsername;
 }
 // Access based on user having a specific permission for the resource ID
 @PreAuthorize("@[Link](authentication,
#resourceId, 'READ')")
 public String readResourceById(String resourceId) {
 // Assumes a bean named 'permissionService' exists with the specified method

🔹 return "Reading resource: " + resourceId;

 }
 }
 8.4. @PostAuthorize
 Uses SpEL to enforce authorization after method execution, often based on the
method's return value.22 The returnObject variable is available in the expression.22
🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link]; // Assume Document has an 'owner'
field

🔹 @Service

 public class DocumentService {


 // Method executes, then checks if the returned document's owner is the current user
 // OR if the current user is an ADMIN.
 @PostAuthorize("[Link] == [Link] or hasRole('ADMIN')")
 public Document getDocumentById(Long id) {
 // ... logic to retrieve document from database ...
 Document doc = findDocumentInDb(id); // Placeholder
 return doc;
 }
 private Document findDocumentInDb(Long id) { /* retrieve logic */ return new
Document(id, "user");} // Dummy
 }
 // Dummy Document class
 class Document {
 public Long id; public String owner;
 public Document(Long id, String owner) { [Link] = id; [Link] = owner; }
 }
 8.5. @PreFilter
 Filters a collection-like method argument before execution using SpEL.22 filterObject
refers to the current element being evaluated.67 Use filterTarget attribute if multiple
collection arguments exist.

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link]; // Assume Item has an 'owner' field
🔹 @Service

 public class ItemProcessingService {


 // Before processing, filter the 'items' list to keep only those owned by the current user.
 @PreFilter("[Link] == [Link]")
 public void processOwnedItems(List<Item> items) {
 [Link]("Processing " + [Link]() + " items owned by " + /* get current
username */ "...");
 // items list inside the method will only contain the filtered elements

🔹 for (Item item : items) {

🔹 [Link](" - Processing item: " + [Link]());

 }
 }
 // Example specifying filterTarget
 @PreFilter(filterTarget = "itemIds", value = "hasAuthority('PROCESS_ID_' +
filterObject)")
 public void processSpecificIds(List<String> itemIds, List<String> userPrefs) {

🔹 [Link]("Processing allowed IDs: " + itemIds);

 // Only itemIds for which the user has PROCESS_ID_{id} authority remain.
 // userPrefs list remains unchanged.
 }
 }
 // Dummy Item class
 class Item {
 public String name; public String owner;
 public Item(String name, String owner) { [Link] = name; [Link] = owner;}
 public String getName() {return name;}
 }
 8.6. @PostFilter
 Filters a returned collection or array after method execution using SpEL.22 filterObject
refers to the current element in the returned collection.68 Be mindful of performance
with large collections.

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link]; // Assume Report has 'isPublic' boolean field

🔹 @Service

 public class ReportService {


 // After retrieving all reports, filter the list to return only public reports
 // OR reports owned by the current user.
 @PostFilter("[Link] or [Link] == [Link]")
 public List<Report> getAllVisibleReports() {
 // ... logic to retrieve all reports (potentially including private ones) ...
 List<Report> allReports = findAllReportsInDb(); // Placeholder
 [Link]("Retrieved " + [Link]() + " reports initially.");
 return allReports; // The returned list will be filtered by Spring Security
 }
 private List<Report> findAllReportsInDb() { /* retrieve logic */
 // Dummy data
 return [Link](new Report("Public Report 1", "admin", true),
 new Report("User Private Report", "user", false),
 new Report("Admin Private Report", "admin", false))
 .collect([Link]());
 }
 }
 // Dummy Report class
 class Report {
 public String title; public String owner; public boolean isPublic;
 public Report(String t, String o, boolean p) { [Link]=t; [Link]=o; [Link]=p; }
 }
 8.7. @RolesAllowed
 Specifies allowed roles using JSR-250 standard annotation.22 Requires jsr250Enabled =
true in @EnableMethodSecurity. Supports simple role names (conventionally without
ROLE_ prefix here, but depends on configuration).

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
🔹 @Service

 public class BillingService {


 // Requires the user to have the 'MANAGER' role
 @RolesAllowed("MANAGER")
 public void generateBillingReport() {
 [Link]("Generating billing report...");
 }
 // Requires either 'ADMIN' or 'ACCOUNTANT' role
 @RolesAllowed({"ADMIN", "ACCOUNTANT"})
 public void processInvoices() {
 [Link]("Processing invoices...");
 }
 }
 8.8. @AuthenticationPrincipal
 Injects the current authenticated principal object (e.g., UserDetails, custom principal
object, or just username String) into a method parameter.22 Useful for accessing user-
specific details directly.

🔹 Example:

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link]; // Example of a custom
principal
 @RestController
 public class UserInfoController {
 // Inject the standard Spring Security UserDetails object
 @GetMapping("/api/user/details")
 public String getUserDetails(@AuthenticationPrincipal UserDetails userDetails) {
 if (userDetails != null) {

🔹 return "Username: " + [Link]() +

🔹 ", Authorities: " + [Link]();

 }
 return "User not authenticated.";
 }
 // Inject a custom UserDetails implementation (if configured)
 @GetMapping("/api/user/custom-info")
 public String getCustomUserInfo(@AuthenticationPrincipal CustomUserDetails
customUser) {
 if (customUser != null) {

🔹 return "User ID: " + [Link]() + // Access custom methods

🔹 ", Email: " + [Link]();

 }
 return "User not authenticated or not a CustomUserDetails instance.";
 }
 // Inject just the username (String) if configured appropriately or using SpEL
 @GetMapping("/api/user/name")
 public String getUsername(@AuthenticationPrincipal(expression = "username") String
username) {

🔹 return "Current username: " + username;

 }
 }
 // Dummy CustomUserDetails for example
 // import [Link];
 // public class CustomUserDetails extends User {
 // private final Long userId; private final String email;
 // public CustomUserDetails(...) { /* constructor */ }
 // public Long getUserId() { ... } public String getEmail() { ... }
 // }
 8.9. @RoleHierarchy
 Used in configuration (typically on a @Bean method returning RoleHierarchy) to define
relationships between roles (e.g., ADMIN > MANAGER > USER).77 Access decisions using
hasRole or similar in SpEL will then respect this hierarchy.

🔹 Example (Configuration Bean):

🔹 Java

 package [Link];
 import [Link];
 import [Link];
 import [Link];
 import [Link];
 import
[Link]
curity;

🔹 @Configuration

 @EnableMethodSecurity // Needed for method security


 public class SecurityHierarchyConfig {

🔹 @Bean

 public RoleHierarchy roleHierarchy() {


 RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();

🔹 // Define hierarchy: ADMIN implies MANAGER, MANAGER implies USER

 // Spaces around '>' are important. Can define multiple levels.


 [Link]("ROLE_ADMIN > ROLE_MANAGER \n ROLE_MANAGER >
ROLE_USER \n ROLE_ADMIN > ROLE_AUDITOR");
 return hierarchy;
 }
 // Other security beans (UserDetailsService, SecurityFilterChain, etc.)
 }
 // --- Usage Example (in a Service) ---
 package [Link];
 import [Link];
 import [Link];

🔹 @Service

 public class HierarchicalAccessService {


 // Accessible by USER, MANAGER, or ADMIN due to hierarchy
 @PreAuthorize("hasRole('USER')")
 public String getUserLevelData() {
 return "User-level data accessed.";
 }
 // Accessible by MANAGER or ADMIN
 @PreAuthorize("hasRole('MANAGER')")
 public String getManagerLevelData() {
 return "Manager-level data accessed.";
 }
 // Accessible only by ADMIN
 @PreAuthorize("hasRole('ADMIN')")
 public String getAdminLevelData() {
 return "Admin-level data accessed.";
 }
 // Accessible only by AUDITOR (or ADMIN due to hierarchy)
 @PreAuthorize("hasRole('AUDITOR')")
 public String getAuditData() {
 return "Audit data accessed.";
 }
 }

🔹 9. Conclusion

 This report has provided a comprehensive overview, complete with examples, of the
most commonly used annotations in Spring Boot applications, categorized by their
functionalities. These annotations play a vital role in simplifying and enhancing various
aspects of Spring Boot development, from core application setup and bean
management to REST API creation, data persistence with JPA, property configuration,
testing, and security implementation. The declarative nature of annotations reduces
boilerplate code, improves code readability, and empowers developers to build
sophisticated applications with greater efficiency and maintainability. Understanding
and effectively utilizing these annotations, aided by practical examples, is fundamental
for any developer working with the Spring Boot framework.

🔹 Generate Audio Overview

You might also like