Guide for Spring annotations

Guide for Spring annotations

Here you can go for a list of annotations of spring and its purpose

@Bean - Annotated method produces a bean managed by the Spring IoC container

@Component - Marks annotated class as a bean found by the component-scanning and loaded into the application context.It tells Spring to create an instance of the object in the Application Context. It's possible to define any name for the instance, the default is the class name as camel case.

@Controller - Stereotype annotation for presentation layer.Marks annotated class as a bean for Spring MVC containing request handler

@RestController - Marks annotated class as a @Controller bean and adds @ResponseBody to serialize returned results as messages. Used in controllers that will behave as RESTful resources. @RestController is a convenience annotation that combines @Controller and @ResponseBody.

@ResponseBody - Makes Spring to convert the returned object to a response body. This is useful for classes exposed as RESTful resources.

@RequestMapping - Used to map web requests to specific handler classes and methods, based on the URI.

@RequestParam - This annotation is used to bind request parameters to a method parameter in your controller.

@PathVariable - This annotations binds the placeholder from the URI to the method parameter and can be used when the URI is dynamically created or the value of the URI itself acts as a parameter.

@Configuration - Marks annotated class as a Java configuration defining beans. basically it is used on classes that defines beans.

@Service - Marks annotated class as a bean (as convention usually containing business logic)

@Repository - Marks annotated class as a bean (as convention usually providing data access) and adds auto-translation from SQLException to DataAccessExceptions

@PostConstruct - Annotated method is executed after dependency injection is done to perform initialization

@PreDestroy - Annotated method is executed before the bean is destroyed, e.g. on the shutdown

@Import - Imports one or more Java configuration classes @Configuration

@PropertySource - Indicates the location of applicaiton.properties file to add key-value pairs to Spring Environment

@Value - Annotated fields and parameters values will be injected.It is used to inject values into a bean’s attribute from a property file. @Value annotation indicates a default value expression for the field or parameter

@ComponentScan - It makes spring to scan the packages for the @Configuration classess i.e Configures component scanning @Compenent, @Service, etc.

@Lazy - Annotated bean will be lazily initialized on the first usage and only if it is requested.

@Profile - Indicates that beans will be only initialized if the defined profiles are active

@Scope - Defines bean creation scope, e.g. prototype, singleton, etc.

@DependsOn - Explicitly defines a dependency to other beans in terms of creation order

@Order - Defines sorting order if injecting a list of beans, but it does not resolve the priority if only a single bean is expected

@Primary - Annotated bean will be picked if multiple beans can be autowired. It will be used when no name is provided telling Spring to inject an object of the annotated class first. Used along with @Component.

@Conditional - Annotated bean is created only if conditions are satisfied

Additionally available in Spring Boot:

@ConditionalOnBean

@ConditionalOnMissingBean

@ConditionalOnClass

@ConditionalOnMissingClass

@ConditionalOnProperty

@ConditionalOnMissingProperty

@Autowired - Beans are injected into annotated setters, fields, or constructor params.This is known is 'Object by type' since the object to be injected is discovered by its type. The items declared @Autowired need not have to be public.

@Configurable - Used on classes to inject properties of domain objects. Types whose properties are injected without being instantiated by Spring can be declared with @Configurable annotation.

@Qualifier - Specifies the name of a bean as an additional condition to identify a unique candidate for autowiring.The default autowiring is by type, not by name, so when there is more than one bean of the same type then @Qualifier is useful.It provides greater control on the dependency injection process and can be used with @Autowired annotation.

@Resource - Annotation used to inject an object that is already in the Application Context. It searches the instance by name. It also works on setter methods.

@Required - Used to mark class members that are mandatory. The Spring auto-configuration fails if a particular property specified with this annotation cannot be injected.

@Valid - Mark a property, method parameters or return type for validation

@Validated - Variant of @Valid that allows validation of multiple groups, e.g. all fields of an annotated class

@NotNull - Must be not null

@NotEmpty - Must be not null nor empty

@NotBlank - Must be not null and at least one non-whitespace character

@Digits - Must be a number within accepted range

@Past - Must be an instant, date or time in the past

@Future - Must be an instant, date or time in the future

@SpringBootConfiguration - Indicates Spring Boot application @Configuration

@EnableAutoConfiguration -Based on class path settings, property settings, new beans are added by Spring Boot by using this annotation.

@ConfigurationProperties - Provides external binding of key value properties

@ConstructorBinding - Bind properties by using constructor rather than setters

@ConfigurationPropertiesScan - Enables auto-detection of @ConfigurationProperties classes

@SpringBootApplication - This annotation is used to qualify the main class for a Spring Boot project. The class used with this annotation must be present in the base path. @SpringBootApplication scans for sub-packages by doing a component scan. It is Combination of @SpringBootConfiguration, @EnableAutoConfiguration, @ConfigurationPropertiesScan and @ComponentScan.

@EntityScan - Configures base packages to scan for entity classes

@EnableJpaRepositories - Enables auto-configuration of jpa repositories

@EnableTransactionManagement - Enables annotation-driven transaction declaration @Transactional

@Transactional - Annotated methods will be executed in a transactional manner

@Id - Marks annotated field as a primary key of an entity

@GeneratedValue - Provides generation strategy of primary keys

@Entity - Marks annotated class as an entity

@Column - Provides additional configuration for a field, e.g. column name

@Table - Provides additional configuration for an entity, e.g. table name

@PersistenceContext - EntityManger is injected into annotated setters and fields

@Embedded - Annotated field is instantiated as a value of an Embeddable class

@Embeddable - Instances of an annotated class are stored as part of an entity

@EmbeddedId - Marks annotated property as a composite key mapped by an embeddable class

@AttributeOverride - Overrides the default mapping of a field

@Transient - Annotated field is not persistent

@CreationTimestamp - Annotated field contains the timestamp when an entity was stored for the first time

@UpdateTimestamp - Annotated field contains the timestamp when an entity was updated last time

@ManyToOne - Indicates N:1 relationship, the entity containing annotated field has a single relation to an entity of other class, but the other class has multiple relations

@JoinColumn - Indicates a column for joining entities in @ManyToOne or @OneToOne relationships at the owning side or unidirectional @OneToMany

@OneToOne - Indicates 1:1 relationship

@MapsId - References joining columns of owning side of @ManyToOne or @OneToOne relationships to be the primary key of referencing and referenced entities

@ManyToMany - Indicates N:M relationship

@JoinTable - Specifies an association using a join table

@BatchSize - Defines size to lazy load a collection of annotated entities

@FetchMode - Defines fetching strategy for an association, e.g. loading all entities in a single subquery

@EnableWebSecurity - Enables web security

@EnableGlobalMethodSecurity - Enables method security

@PreAuthorize - Defines access-control expression using SpEL, which is evaluated before invoking a protected method

@PostAuthorize - Defines access-control expression using SpEL, which is evaluated after invoking a protected method

@RolesAllowed - Specifies a list of security roles allowed to invoke protected method

@Secured - Java 5 annotation for defining method level security

@EnableAspectJAutoProxy - Enables support for handling components marked with @Aspect

@Aspect - Declares an annotated component as an aspect containing pointcuts and advices

@Before - Declares a pointcut executed before the call is propagated to the join point

@AfterReturning - Declares a pointcut executed if the join point successfully returns a result

@AfterThrowing - Declares a pointcut executed if the join point throws an exception

@After - Declares a pointcut executed if the join point successfully returns a result or throws an exception

@Around - Declares a pointcut executed before the call giving control over the execution of the join point to the advice

@Pointcut - Externalized definition a pointcut expression

@DeclareParents - Declares that matching types should be given new parents,that is, it introduces new functionality into matching types.

spring.profiles.active - Property to be set in application.properties in order to tell Spring what profiles are active.

@Profile("dev") - Annotation used to define which profile can execute the annotated method.

Spring Test

@SpringBootTest - Annotated test class will load the entire application context for integration tests

@WebMvcTest - Annotated test class will load only the web layer (service and data layer are ignored)

@DataJpaTest - Annotated class will load only the JPA components

@Transactional - Describes transaction attributes on a method or class.

@AfterTransaction - Annotation used to identify which method needs to be invoked after a transaction is completed.

@BeforeTransaction - Used to identify the method to be invoked before a transaction starts executing.

@Rollback - Indicates if the transaction of a test method must be rolled back after the execution of the test completed.

@DirtiesContext - This annotation indicates the test(s) modify or corrupt the SpringApplicationContext and that it should be closed. Hence, context is reloaded before the next test is executed. Indicates that annotated tests dirty the application context and will be cleaned after each test

@ExpectedException - The test method is expected to throw a particular exception, else the test fails.

@WebAppConfiguration - Used to create web version of the application context.

@Repeat - Specifies the test method to be executed multiple times.

@Commit - Indicates that the transaction of a test method must be committed after the execution of the test completed.

@Timed - Indicates the time limit for the test method. If the test has not completed execution before the time expires, the test fails.

@TestPropertySource - Annotation specifies the property sources for the test class.

@MockBean - Marks annotated field as a mock and loads it as a bean into the application context

@SpyBean - Allows partial mocking of beans

@Mock - Defines annotated field as a mock

@ContextConfiguration - Defines @Configuration to load application context for integration test.The location of the configuration file has to be povided to Spring.

@ExtendWith - Defines extensions to execute the tests with, e.g. MockitoExtension

@SpringJUnitConfig - Combines @ContextConfiguration and @ExtendWith(SpringExtension.class)

@TestPropertySource - Defines the location of property files used in integration tests

@ActiveProfiles - Defines which active bean definition should be loaded when initializing the test application context

@Sql - Allows defining SQL scripts and statements to be executed before and after tests

Thanks for reading it.