Spring Annotations
Spring Annotations
1. Core Annotations
Annotation Purpose
@Component
Marks a class as a Spring-managed component. Generic stereotype for
Spring beans.
@Service Specialization of @Component , used for service-layer beans.
Indicates the primary bean to use when multiple beans of the same
@Primary
type exist.
@Scope Defines the scope of a bean ( singleton , prototype , etc.).
@Lazy Specifies lazy initialization for a bean.
@Value Injects values from property files or environment variables.
@PostConstruct Indicates a method to be executed after bean initialization.
@PreDestroy Indicates a method to be executed before bean destruction.
@EventListener Handles Spring application events.
@PropertySource Specifies the location of property files.
@CrossOrigin
Enables Cross-Origin Resource Sharing (CORS) for RESTful
services.
@ExceptionHandler Handles exceptions thrown by controller methods.
@InitBinder Customizes data binding for request parameters.
@ControllerAdvice A global exception handler for all controllers.
Annotation Purpose
@Transactional Marks a method or class to participate in a transaction.
@PersistenceContext Injects a JPA EntityManager .
@Repository
Marks a class as a DAO component with exception
translation.
@Query Defines custom queries in Spring Data repositories.
Combines @Configuration ,
@SpringBootApplication
@EnableAutoConfiguration , and @ComponentScan .
7. Security Annotations
Annotation Purpose
@EnableWebSecurity Enables Spring Security for the application.
@Secured Specifies role-based security for methods.
@PreAuthorize Adds pre-authorization checks to methods.
@PostAuthorize Adds post-authorization checks to methods.
@RolesAllowed Specifies allowed roles for accessing a method.
9. Testing Annotations
Annotation Purpose
@SpringBootTest Loads the full Spring context for integration testing.
@WebMvcTest Focuses testing on Spring MVC components (e.g., controllers).
@MockBean Creates mock beans in the Spring context.
@TestConfiguration Defines test-specific configuration classes.
@DataJpaTest Tests JPA repositories with an in-memory database.