Spring Annotations Concisely Explained
Our Tech Blog – Current and interesting topics about our work
In our tech blog, we share practical insights into IT, current trends and useful lessons from our daily work. Whether it is innovative software solutions, best practices in digitalization or reports from successful projects – here you will regularly find new articles that keep you up to date. Stop by and discover how we use technology to make businesses more efficient and future-proof.
Comprehensive Guide to Spring Framework and Spring Boot Annotations
Comprehensive Guide to Spring Framework and Spring Boot Annotations
The Spring Framework and Spring Boot are central pillars in Java development. They provide a variety of annotations that allow developers to build robust and efficient applications. This guide provides a detailed overview of the various annotations and their applications.
Core Spring Annotations
- @Bean: Designates a method that generates a bean managed by the Spring IoC container.
- @Component: Marks a class as a bean that is found by component search and loaded into the application context.
- @Controller: Marks a class as a bean for Spring MVC that contains request handlers.
- @RestController: Marks a class as @Controller Bean and adds @ResponseBody to serialize the return results as messages.
- @Configuration: Marks a class as a Java configuration that defines beans.
- @Service: Marks a class as a bean that usually contains business logic.
- @Repository: Marks a class as a Bean for data access and adds an automatic conversion from SQLException to DataAccessExceptions.
Bean state annotations
- @PostConstruct: Runs after dependency injection to perform initializations.
- @PreDestroy: Runs before the bean is destroyed, such as when the application is shut down.
configuration annotations
- @Import: Imports one or more Java configuration classes.
- @PropertySource: Specifies the location of the application.properties file to add key value pairs to the Spring environment.
- @Value: Injects values into annotated fields and parameters.
- @ComponentScan: Configures component search for @Component, @Service, etc.
Bean properties Annotations
- @Lazy: The annotated bean is initialized with a delay on first use.
- @Profile: Beans are only initialized if the defined profiles are active.
- @Scope: Defines the creation area of the bean, e.g. prototype, singleton, etc.
- @DependsOn: Defines explicitly a dependency on other beans in terms of the creation order.
- @Order: Defines the sorting order when a list of beans is injected.
- @Primary: The annotated bean is selected if several beans are eligible for the autowiring.
- @Conditional: The annotated bean is created only if the conditions are met.
- @ConditionalOnBean: The condition is met if one or more specified beans are present in the Spring ApplicationContext. This is often used to customize the configuration based on the availability of certain beans.
- @ConditionalOnMissingBean: Unlike @ConditionalOnBean, this condition is met if there is no Bean of the specified type in the ApplicationContext. This is useful to ensure that a certain configuration loads only if the required bean is missing.
- @ConditionalOnClass: This annotation checks the presence of a particular class or classes in the class path. If the class exists, the condition is met. This is often used to control auto-configurations based on the availability of classes from external libraries.
- @ConditionalOnMissingClass: The opposite of @ConditionalOnClass, this condition is met if a certain class does not exist in the class path. This can be used to omit certain configurations if a required dependency is missing.
- @ConditionalOnProperty: This annotation allows configuration based on the presence and value of environment variables or properties. It is a powerful tool to control configurations in different environments, such as development, testing and production.
- @ConditionalOnMissingProperty: Similar to @ConditionalOnProperty, but the condition is met if a certain property (property) is not defined or has a specific, untrue value. This is used to load a configuration only if a specific property is not set.
Spring Boot-specific annotations
- @SpringBootConfiguration: Designates a Spring Boot application configuration.
- @EnableAutoConfiguration: Allows automatic configuration of the application context based on the class path.
- @ConfigurationProperties: Provides external binding of key-value properties.
- @ConstructorBinding: Binds properties using the constructor instead of using the setter.
- @ConfigurationPropertiesScan: Allows automatic recognition of @ConfigurationProperties classes.
- @SpringBootApplication: Combination of @SpringBootConfiguration, @EnableAutoConfiguration, @ConfigurationPropertiesScan and @ComponentScan.
- @EntityScan: Configures basic packages for scanning entity classes.
- @EnableJpaRepositories: Allows automatic configuration of JPA repositories.
Bean injection annotations
- @Autowired: Beans are injected into annotated setters, fields or constructor parameters.
- @Qualifier: Specifies the name of a bean as an additional condition for identifying a unique candidate for autowiring.
Validation annotations
- @Valid: Indicates a property, method parameter or return type for validation.
- @Validated: Variant of @Valid that allows the validation of multiple groups.
Spring Boot test annotations
- @SpringBootTest: loads the entire application context for integration tests.
- @WebMvcTest: Only loads the web layer for tests.
- @DataJpaTest: Only loads the JPA components for tests.
Transaction notations
- @EnableTransactionManagement: Allows declarative transaction management.
- @Transactional: Methods provided with this annotation are executed in a transaction.
- Methods and Class Level: When applied at class level, all public methods of the class become transactional.
- Transaction Management: With an annotated method, Spring starts a new transaction before the method is executed and terminates the transaction after the method is executed. This includes the commit or rollback of the transaction, depending on whether the execution was successful or an exception was triggered.
- Isolation and Propagation: The annotation allows different transaction characteristics such as isolation level and propagation behavior to be adjusted. The isolation level defines how transactions are isolated from each other, and the propagation behavior determines how transactions are handled with respect to ongoing transactions.
- Rollback Rules: By default, throwing a RuntimeException will result in a rollback of the transaction, while checked exceptions will not.
- Proxy-based behavior: In Spring, transaction management is often implemented by proxies. This means that transaction logic is added when an object is encapsulated by a proxy. This affects the visibility and behavior of transactional methods within the same class.
- Data sources and transaction managers: For JDBC, JPA, Hibernate or other persistence technologies, different transaction managers can be configured.
- Spring Boot Configuration: In Spring Boot applications, transaction management is often configured automatically. Nevertheless, the configuration can be further refined by specifying own transaction managers or adjusting the transaction properties.
Spring JPA and Hibernate Annotations
- @Entity: Marks a class as an entity in the database.
- @Table: Specifies the table in the database that corresponds to the entity.
- @Id: Indicates a field as the primary key of the entity.
- @GeneratedValue: Specifies the strategy for generating the primary key values.
- @Column: Defines specific properties of a column in the database table.
- @ManyToOne, @OneToMany, @OneToOne, @ManyToMany: Define the different types of relationships between entities.
- @JoinColumn: Specifies the column for joining in relationships.
- @Embedded and @Embeddable: Allow to use a class as part of another entity.
- @MappedSuperclass: Allows you to inherit properties in JPA entities.
- @Transactional: Specifies that a method or an entire class should be executed in a transaction context.
Spring Security Annotations
- @EnableWebSecurity: Enables web security in a Spring application.
- @PreAuthorize and @PostAuthorize: Define security conditions before or after the execution of a method.
- @Secured: Restricts access to methods based on roles.
- @RolesAllowed: Specifies which security roles have access to a method.
Spring AOP Annotations
- @Aspect: Marks a class as an aspect for cross-cutting concerts.
- @Before, @After, @AfterReturning, @AfterThrowing, @Around: Define different types of advice (advices) in AOP.
- @Pointcut: Defines a pointcut expression.
- @EnableAspectJAutoProxy: Allows support for aspects with automatic proxy generation.