I'm always excited to take on new projects and collaborate with innovative minds.

Email

contact@niteshsynergy.com

Website

https://www.niteshsynergy.com/

Spring Boot Related Annotations

This guide explains key Spring annotations with concise descriptions and updated code snippets for practical implementation. Each section is organized by categories: Spring Core, Spring MVC, and Spring Boot, providing clarity and examples in Java and Spring Boot.

1. Spring Core Annotations

1.1. @Configuration

Used to define configuration classes in Spring. Equivalent to XML configuration.

image-18.png

1.2. @ComponentScan

Used to specify packages to scan for Spring-managed components.

image-19.png

1.3. @Autowired

Automatically injects dependencies. Can be used on constructors, fields, or setters.

image-20.png

1.4. @Component

Marks a class as a Spring-managed component.

image-21.png

1.5. @Bean

Defines a Spring-managed bean directly in a configuration class.

image-22.png

1.6. @Qualifier

Resolves ambiguity when multiple beans of the same type exist.

image-23.png

1.7. @Primary

Gives higher precedence to a bean when multiple beans of the same type exist.

image-24.png

1.8. @Value

Injects property values into fields.

image-25.png

1.9. @Lazy

Delays bean initialization until it is first accessed.

image-26.png

1.10. @Scope

Defines the scope of a bean (singleton, prototype, etc.).

image-27.png

1.11. @Profile

Defines profiles for conditional bean registration.

Code Example:

image-28.png

 

2. Spring MVC Annotations

2.1. @Controller

Indicates a class is a controller in an MVC application.

image-29.png

 

2.2. @RestController

Combines @Controller and @ResponseBody for REST APIs.

Code Example:

image-30.png

2.3. @RequestMapping

Maps HTTP requests to handler methods.

image-31.png

2.4. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

Simplified request mappings for specific HTTP methods.

Code Example:

image-32.png

2.5. @ExceptionHandler

Handles exceptions thrown in controller methods.

image-33.png

3. Spring Boot Annotations

3.1. @SpringBootApplication

Main annotation for bootstrapping Spring Boot applications.

image-34.png

3.2. @EnableAutoConfiguration

Enables auto-configuration in Spring Boot.

Code Example:

image-35.png

3.3. @ConditionalOnProperty

Loads a bean based on property conditions.

Code Example:

image-36.png

3.4. @ConditionalOnClass

Loads a bean if a specific class is present.

Code Example:

image-37.png

 

4. JPA Annotations

4.1. @Entity

Marks a class as a JPA entity (mapped to a database table).

Code Example:

image-38.png

 

4.2. @Table

Specifies the database table name for an entity.

Code Example:

image-39.png

 

4.3. @Id and @GeneratedValue

Marks a field as the primary key and defines its generation strategy.

Code Example:

image-40.png

4.4. @Column

Customizes column attributes in the database.

Code Example:

image-41.png

4.5. @OneToOne, @OneToMany, @ManyToOne, @ManyToMany

Defines relationships between entities.

Code Example (OneToMany):

image-42.png

4.6. @JoinColumn

Specifies the foreign key column in a relationship.

Code Example:

image-43.png

4.7. @Embeddable and @Embedded

Used for reusable fields as embedded objects.

image-44.png

4.8. @NamedQuery

Defines a named JPQL query.

Code Example:

@Entity
@NamedQuery(name = "Employee.findByDepartment", query = "SELECT e FROM Employee e WHERE e.department = :department")
public class Employee {
}
 

5. Spring Boot and General Service Annotations

5.1. @Service

Marks a class as a Spring-managed service bean.

Code Example:

image-45.png

5.2. @Repository

Specialized @Component for persistence logic, enables exception translation.

Code Example:

image-46.png

5.3. @RestControllerAdvice

A combination of @ControllerAdvice and @ResponseBody for handling exceptions in REST APIs.

Code Example:

image-47.png

5.4. @EnableJpaRepositories

Enables JPA repository support.

Code Example:

image-48.png

5.5. @Transactional

Ensures methods execute within a transaction context.

Code Example:

image-49.png

6. Microservices Annotations

6.1. @EnableEurekaClient

Registers a microservice as a Eureka client.

Code Example:

image-50.png

6.2. @FeignClient

Enables declarative REST client for communication between services.

Code Example:

image-51.png

6.3. @LoadBalanced

Adds client-side load balancing to a RestTemplate.

Code Example:

image-52.png

6.4. @CircuitBreaker

Handles fallback for failed service calls in Resilience4j.

Code Example:

image-53.png

 

6.5. @Retry

Retries failed calls in Resilience4j.

Code Example:

image-55.png

6.6. @EnableHystrix

Enables Hystrix Circuit Breaker in microservices.

Code Example:

image-56.png

 

6.7. @EnableZuulProxy

Marks a microservice as a Zuul API Gateway.

Code Example:

image-57.png

1. Circuit Breaker Related

1.1. @CircuitBreaker

Handles failures with fallback logic using Resilience4j.

image-58.png

1.2. @Retry

Retries a failed request with a configurable number of attempts.

Code Example:

image-59.png

1.3. @RateLimiter

Limits the number of requests to prevent service overloading.

Code Example:

image-60.png

1.4. @Bulkhead

Isolates resources to prevent overloads.

Code Example:

image-61.png

 

2. API Gateway Logging

2.1. Global Logging Filter for Zuul Gateway

Log incoming and outgoing requests at the API Gateway level.

Code Example:

image-62.png
image-63.png

2.2. Spring Cloud Gateway Filter

Log requests and responses using GlobalFilter.

Code Example:

image-64.png

3. Kafka Related Annotations

3.1. @EnableKafka

Enables Kafka-related configurations.

image-65.png

3.2. @KafkaListener

Listens to messages from a Kafka topic.

Code Example:

image-66.png

3.3. @KafkaHandler

Used for handling multiple message types in a Kafka listener.

Code Example:

image-67.png

4. Messaging Queue Related

4.1. @RabbitListener (RabbitMQ)

Listens for messages from RabbitMQ queues.

Code Example:

image-68.png

4.2. @JmsListener (ActiveMQ)

Listens for messages from ActiveMQ queues.

Code Example:

image-69.png

5. Spring Security Related Annotations

5.1. @EnableWebSecurity

Enables Spring Security.

Code Example:


Note: **Deprecated**

image-70.png

5.2. @PreAuthorize

Adds method-level security based on roles or expressions.

Code Example:

image-71.png

5.3. @Secured

Simpler version of @PreAuthorize for role-based security.

Code Example:

image-72.png

5.4. @RolesAllowed

Defines roles allowed for a method (JSR 250).

Code Example:

image-73.png

5.5. @EnableGlobalMethodSecurity

Enables method-level security annotations like @PreAuthorize.

Code Example:

image-74.png

5.6. @WithMockUser

Used in testing to mock authenticated users.

Code Example:

image-75.png

1. JUnit Annotations

1.1. @Test

Marks a method as a test method.

image-76.png

1.2. @BeforeEach

Runs before each test method.

Code Example:

image-77.png

1.3. @AfterEach

Runs after each test method.

Code Example:

image-78.png

 

image-79.png

1.4. @BeforeAll

Runs once before all test methods (static method).

Code Example:

image-80.png

1.5. @AfterAll

Runs once after all test methods (static method).

Code Example:

image-81.png

1.6. @Disabled

Disables a test method or class.

Code Example:

image-82.png

1.7. @ParameterizedTest

Runs the same test with multiple sets of input.

Code Example:

image-83.png

2. Mockito Annotations

2.1. @Mock

Creates a mock object.

Code Example:

image-84.png
image-85.png

2.2. @InjectMocks

Injects mock objects into the class being tested.

Code Example:

image-86.png
image-87.png

2.3. @Spy

Creates a partial mock (real methods + mock behavior).

Code Example:

image-88.png

2.4. @Captor

Captures arguments passed to mock methods.

Code Example:

image-89.png
image-90.png

2.5. @RunWith

Specifies a test runner (JUnit 4).

Code Example:

image-91.png

2.6. @ExtendWith

Specifies a test runner (JUnit 5).

Code Example:

image-92.png

 

1. @ParameterizedTest

This annotation enables running the same test with multiple sets of input data. It works alongside various data sources like @ValueSource, @EnumSource, and @MethodSource.

2. @ValueSource

Provides an array of literal values as input.

Code Example:

image-93.png

3. @EnumSource

Provides enum constants as input.

Example Enum:

image-94.png
image-95.png

4. @MethodSource

Provides test data using a static method from the same or a different class.

Code Example:

image-96.png
image-97.png

5. @CsvSource

Provides input as comma-separated values.

Code Example:

image-98.png

6. @CsvFileSource

Provides input from an external CSV file.

Example File (data.csv):

image-99.png
image-100.png

7. Combining Annotations

Using @MethodSource with Custom Data Classes:

Code Example:

image-101.png
image-102.png
image-103.png
4 min read
Nov 17, 2024
By Nitesh Synergy
Share

Leave a comment

Your email address will not be published. Required fields are marked *