DEV Community

Pablo Cavalcante
Pablo Cavalcante

Posted on

8

Spring Framework  - Overview of main modules and annotations.

What is Spring Framework?

The Spring Framework is one of the most popular and powerful frameworks in the Java ecosystem, widely used in the development of enterprise, web, and microservices applications. Originally created to facilitate the development of decoupled Java applications through dependency injection, the Spring Framework has evolved into a complete ecosystem with dozens of specialized modules.

In this article, we will explore the main components of the Spring Framework, their functionalities, and the most used annotations for each module. However, before we delve deeper into this powerful tool, let's understand the Inversion of Control (or IoC) design principle on which Spring is based.

What is Inversion of Control?

Inversion of Control (IoC) is the principle in which the creation and management of the lifecycle of dependencies is done by external code, often a container (Spring IoC Container in the case of Spring), instead of being done directly in the code that is using these dependencies. The main purpose of this principle is to minimize code coupling, increasing the maintainability, extensibility and testability of the code.

Well, Inversion of Control is a principle, as said before, but how does Spring apply this principle? Spring applies this principle by implementing the Dependency Injection Design Pattern, which is one of the ways to apply this principle (Yes, there are other ways to do this).

Dependency Injection

In simple terms, Dependency Injection is an implementation of the Inversion of Control principle that provides instances of dependencies that classes need without them having to create or manage their own life cycles. For us in the Java community with Spring, these are the famous beans.

A bean is nothing more than a component instantiated, configured and managed by the Spring IoC Container. When a class is registered as a bean, Spring takes care of its life cycle, creation, dependency injection, destruction, etc. We can create beans through of the annotations that Spring makes available to us: @Component, @Service, @Repository, @Controller (or @RestController).

Another way to create beans is, in a configuration class annotated with @Configuration, to annotate with @Bean in a method that returns the instance of a class that you want Spring to manage.

We can apply dependency injection in one of the following ways:

Class attribute

Using the @Autowired annotation on a class attribute, we perform field injection. The @Autowired annotation defines a point where dependency injection will be performed.

@Service
public class Service {

    @Autowired
    private Repository repository;

    // construtor, getters e setters
}
Enter fullscreen mode Exit fullscreen mode

It's worth mentioning that Field Injection is not a way of applying dependency injection recommended by the Spring team. Learn more in this article: Spring Field Injection Const.

Class constructor

In constructor injection, we simply declare the dependencies in the class constructor and then assign them to the attributes. This is how we usually instantiate a class in everyday life. The advantages of this injection method are increased code readability, ease of maintenance, and ease of building tests.

@Service
public class Service {

    private Repository repository;

    public Service(Repository repository) {
        this.repository = repository;
    }
    // …
}
Enter fullscreen mode Exit fullscreen mode

This is the way recommended by the Spring team.

Setter Method

In setter injection, we create a default setter method and add the @Autowired annotation. That's it.

@Service
public class Service {

    private Repository repository;

    @Autowired
    public void setRepository(Repository repository) {

    this.repository = repository
    }
}
Enter fullscreen mode Exit fullscreen mode

Ok, now that we have seen what Inversion of Control is and how Spring implements this principle (using the Dependency Injection Design Pattern - DI) and how we can apply it, let's look at some of the main modules of this framework along with one of the most wonderful things about Spring and the focus of this article: annotations. Our lives are much easier with the annotations that Spring modules provide us. Really! Seriously!

Note: Spring modules are not only made up of annotations, but also of classes, interfaces, etc. The focus of this article is on annotations. Therefore, if you want to know more about each module, I recommend looking at the official Spring documentation.

Spring Boot

Spring Boot is an extension of the Spring Framework that abstracts, through convention over configuration, all the configuration overhead of web applications and microservices (“just run” philosophy), that is, we don’t need to worry much about configurations to make the application build and run. With Spring Boot:

  • We eliminate the need for extensive configuration (like giant XMLs).
  • We achieve "quick start" of projects based on the Spring Framework.
  • We have a built-in server, usually TomCat.
  • We have intelligent autoconfiguration based on what is in the classpath.
  • We generate standalone executables (.jar) so that we can run the application with a simple java -jar.

Spring Boot Starters

Spring Boot starters are sets of pre-configured dependencies packaged together to solve specific use cases. Because they are pre-configured, they reduce the complexity of manually configuring the application. For example:

<dependency>
     <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

This starter includes:

  • Spring MVC.
  • Jackson (for JSON).
  • Embedded Tomcat.
  • And other dependencies for building web APIs.

In other words, with a dependency declared in pom.xml, you already have everything you need to start building a REST API. Cool, right? That's awesome!

Main Spring Boot Starters

Web

  • spring-boot-starter-web
  • spring-boot-starter-webflux
  • spring-boot-starter-thymeleaf
  • spring-boot-starter-mustache

Persistence and Databases

  • spring-boot-starter-data-jpa
  • spring-boot-starter-jdbc
  • spring-boot-starter-data-mongodb
  • spring-boot-starter-data-redis
  • spring-boot-starter-data-elasticsearch

Security and Authentication

  • spring-boot-starter-security
  • spring-boot-starter-oauth2-client
  • spring-boot-starter-oauth2-resource-server

Tests

  • spring-boot-starter-test

Others starters

  • spring-boot-starter-actuator
  • spring-boot-starter-validation
  • spring-boot-starter-mail
  • spring-boot-starter-amqp
  • spring-boot-starter-logging

Now that we've seen some of the main Spring Boot starters, how about we take a look at the amazing annotations for each module and what each annotation does? Let's go!

Annotations

Before we continue to make the annotations in Java and the Spring ecosystem, we need to understand what they are. This annotation is a powerful resource for configuring and modifying the behavior of classes, methods, fields and parameters, often without the need to write additional code.

The annotations are mainly supported by the Design Pattern Metadata, but their practical application is also associated with the use of two Proxy patterns, Reflection, Inversion Control (IoC) and Decorator, especially within Spring.

The annotations have the following syntax: @. For example, in Spring we have to annotate @Component, @Autoriwed, @Service, @Repository, etc. The annotations always start with the @ character. They can also receive arguments, as in a method.

In Java, we can create our own annotations with @interface. See an example:

Method annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyCustomAnnotation { }
Enter fullscreen mode Exit fullscreen mode
  • @Retention(RetentionPolicy.RUNTIME) - The annotation that we are creating is available during code execution.
  • @Target(ElementType.METHOD) - restricts the use of annotation to only methods.
public class MyClass {

    @MyCustomAnnotation
    public void execute() { }
}
Enter fullscreen mode Exit fullscreen mode

The above annotation was created to be used in class methods, but we can also use classes and attributes as well.

The use of annotations have advantages and disadvantages:

Advantages

  • We do not need to repeat common configurations or behaviors.
  • It allows us to add dynamic behaviors based on metadata.
  • The code becomes more expressive.

Disadvantages

  • May impact application performance.
  • When we use framework annotations, we couple our code to it.
  • The logic of the hidden annotations.

Well, now that we saw or what, for what purpose and how we can create the annotations in Java, how about we see the main annotations of each module of the Spring ecosystem? Let's go! (Now it's serious!)

Just a small observation: it may be that you have placed an annotation that, in truth, belongs to another module, but don't worry, its functionality continues as described.

Spring Boot Web/MVC

Spring Web is used to build web applications, including RESTful, using Spring MVC. It is essential for creating web applications based on the Spring Framework.

Furthermore, it is a module that helps create web applications in an easy, simple and elegant way, or that makes it possible to build robust and flexible web applications and, as the name suggests, is based on an MVC pattern.

In Spring MVC, a controller is created using @Controller or @RestController annotations and for each method there is a mapping to the URL that the controller will be called.

The main annotations are:

  • @SpringBootApplication - combines @Configuration, @EnableAutoConfiguration and @ComponentScan. In this way, we do not need to install a web server, just Spring Boot or an embedded Tomcat server.
  • @EnableAutoConfiguration - active or automatic configuration resource based on classpath.
  • @ComponentScan – used to scan packets for beans.
  • @ConfigurationProperties - binds external properties (application.properties file) to POJO objects.
  • @EnableConfigurationProperties - activate or use @ConfigurationProperties.
  • @ConditionalOnProperty - activating a bean/configuration if a property is present.
  • @ConditionalOnClass - activates a certain class in the classpath.
  • @ConditionalOnMissingBean - activate if the bean is not present.
  • @SpringBootTest - used for integration tests with full context.
  • @Configuration - define a class as a source of bean definitions.
  • @Bean - used in methods of annotated classes, generally, with @Configuration indicating the Spring Container IoC that the instance returned by which method should be managed by it.
  • @Value - is used to insert values ​​into fields, methods or constructor parameters, usually from configuration files.
  • @Autowired - defines dependency injection points within a class.
  • @Scope - defines the lifetime of an object managed by the Spring Framework. We can combine with other annotations like @Component or @Bean.
  • @Primary - it is used when we need to guide Spring on what class should be the injection pad when we have a context that we have two or more beans with the same type. It is very common to also use the @Qualifier annotation also in context to indicate which instance to use instead of deixar or Spring to attach to the parent instance.
  • @Profile - defines which profile a bean should be loaded for. Commonly, there are classes that only need to be carried out in a development, testing, homologation or production environment.
  • @Component - indicates to Spring that the class instance will be created and managed by it.
  • @Service - defines a class of service. There is a semantic extension of @Component annotation.
  • @RestControllerAdvice - combination of @ControllerAdvice and @ResponseBody annotations. It indicates to Spring that it is an exceptionally specialized component and that the return two methods must be inserted in the body of the HTTP response and converted to JSON.
  • @ControllerAdvice - Check with exceptions to a Spring MVC application. It is used for global error manipulation. Have full control over the response body and status code.
  • @RestController - defines a class containing methods for a RESTful API. It's combines @Controller and @ResponseBody.
  • @RequestMapping - map REST requirements for methods or classes.
  • @Controller - defines a class containing methods for the Spring MVC structure.
  • @RequestBody – map the body of the HTTP request to an object.
  • @PathVariable – map URL parts - parameters - as they vary.
  • @RequestParam – map parameters (query strings) to the request for variables.
  • @ExceptionHandler – defines methods that handle specific exceptions.
  • @ResponseStatus – with this annotation, we can specify the desired HTTP status of the response.
  • @ModelAttribute - binds form data to objects.
  • @CrossOrigin - activates cross-domain communication for request manipulation methods.
  • @SessionAttributes - declares the session attributes by listing the names of two model attributes that must be transparently stored in the session, serving as form support beans between subsequent requests.
  • @GetMapping - map HTTP GET requirements to methods or classes of a controller.
  • @PostMapping - map HTTP POST requirements to methods or classes of a controller.
  • @PutMapping - map HTTP PUT requirements to methods or classes of a controller.
  • @DeleteMapping - map HTTP DELETE requirements to methods or classes of a controller.
  • @PatchMapping - map HTTP PATCH requirements to methods or classes of a controller.

Spring Doc OpenAPI

Spring Doc OpenAPI is a library that integrates Spring Boot with the OpenAPI 3 specification, allowing the automatic generation of documents of its REST API based on the annotations of two Spring drivers. It is a modern alternative to Springfox (Swagger 2) and provides full support for OpenAPI 3 with minimal configuration. With this, we can generate:

  • OpenAPI specification in JSON/YAML at execution time (/v3/api-docs).
  • A Swagger UI interface in real time (/swagger-ui.html or /swagger-ui/index.html).
  • Support Grouped APIs, security, versioning and more.

The main annotations are:

  • @OpenAPIDefinition - defines the global API documentation (info, servers, tags, etc).
  • @Info - API information (title, description, version, etc.).
  • @Contact - contact information for the API.
  • @License - data from the license of the API.
  • @Server - defines API servers (ex: base URL).
  • @Servers - defines multiple servers.
  • @ExternalDocumentation - defines a link for external documentation.
  • @Tag - defines reused tags.
  • @Tags - allows multiple tags to be applied to a controller.
  • @Operation - defines an API operation (GET, POST, etc).
  • @ApiResponse - defines a possible response to the operation.
  • @ApiResponses - defines multiple responses for an operation.
  • @RequestBody - descreve o body da requisição.
  • @Parameter - defines a parameter of rota, query, header or cookie.
  • @Parameters - allows multiple parameters.
  • @SecurityRequirement - assume that security schemes are applied to operations.
  • @SecurityScheme - defines a security scheme (ex: JWT, OAuth2, etc).
  • @SecuritySchemes - allows you to declare multiple security schemes.
  • @Hidden - hides a class, method, parameter, etc. of the documentation.
  • @Links - defines links between operations.
  • @Link - a link between responses and other operations.
  • @Callback - remove asynchronous callbacks (ex: webhooks).
  • @Callbacks - define multiple callbacks.
  • @Extension - allows adding custom properties to the OpenAPI.
  • @Extensions - allows multiple extensions.

Spring Data e Spring Data JPA

Spring Data JPA is intended to facilitate the integration and use of JPA (Java Persistence API) in Java applications. It is one of the extensions of Spring Data. With him:

  • Simplify access to related data using JPA.
  • Reduce boilerplate code (repetitive code).
  • Provide a declarative interface to create data repositories.
  • Help implement dynamic and customized queries in a simple way.
  • Integrate with SQL databases through a layer of abstraction.

The main annotations are:

  • @Transactional – configures the transactional behavior of a method.
  • @NoRepositoryBean – so that the Spring Framework does not create common repository interface beans for file repositories.
  • @Repository – defines a repository bean (it is not part of Spring Data, but is associated with it).
  • @Query – used to provide a JPQL implementation for a repository method.
  • @Param – defines named parameters that will be passed for queries.
  • @Id – defines that the attribute is an identifier.
  • @Transient – ​​marks a field of a model class as transient. Therefore, the dice arming mechanism is not the gravel or value of this field.
  • @GeneratedValue – defines that the management of the entity id will be managed by the persistence provider (JPA).
  • @Entity - Mark a class as a JPA entity. Com isso, a classe tem seu state managed by context of underlying persistence.
  • @Table – specifies the table of the annotated entity.
  • @Column – specifies the mapping between a basic attribute and the column of the data bank table.
  • @Lob – specifies which attribute currently annotated represents a type of large object.
  • @OneToOne – specifies a dice bank relationship one to one .
  • @ManyToOne – specifies a multiple dice bank relationship for um.
  • @OneToMany – specifies a dice bank relationship for many.
  • @ManyToMany – specifies a data bank relationship many to many.
  • @JoinColumn – specifies the FOREIGN KEY column used to enter an association of entities or an incorporated collection.
  • @JoinTable – specifies a link table between two other data bank tables.
  • @MapsId – specifies that the identity identifier is mapped to the currently annotated @ManyToOne or associated @OneToOne.
  • @ElementCollection – specifies a collection of basic or incorporated types.
  • @Embeddable – specifies embedded types. As well as the basic types, the types are incorporated without their identity, being managed by their proprietary entity.
  • @Embedded – specifies that a given entity attribute represents an embedded type.
  • @Enumerated – specifies that an entity attribute represents an enumerated type.
  • @JoinColumns – used to group several @JoinColumn annotations that are only used to map an association of entities or an incorporated collection using a composite identifier.
  • @NamedQuery – specifies a JPQL query that can be retrieved later by its name.
  • @OrderBy – specifies the attributes of the entity used to classify and search for the currently annotated collection.
  • @PersistenceContext – specifies the EntityManager that needs to be grafted as a dependency.
  • @Temporal – specifies the time type of the java.util.Date or java.util.Calendar entity attribute.
  • @Access – specifies the access type of the associated entity class, associated superclass, or embedded entity class attribute.
  • @Inheritance – specifies the inheritance strategy of a given hierarchy of entity classes.
  • @ForeignKey – specifies the foreign key associated with the @JoinColumn mapping.
  • @Mapkey – specifies the key of a java.util.Map association for which type of key is the primary key or attribute of the entity that represents the value of the map.
  • @NamedQueries – used to group various @NamedQuery annotations.
  • @PersistenceUnit – specifies the EntityManagerFactory that needs to be grafted as a dependency.
  • @PersistenceUnits – used to group various @PersistenceUnit annotations.
  • @PostLoad – specifies a call return method that is activated after an entity is loaded.
  • @PostPersist – specifies a call return method that is activated after an entity is persisted.
  • @PostRemove – specifies a callback method that is activated after an entity is removed.
  • @PostUpdate – specifies a call return method that is activated after an entity is updated.
  • @PrePersist – specifies a call return method that is activated before an entity is persisted.
  • @PreRemove – specifies a call return method that is activated before an entity is removed.
  • @PreUpdate – specifies a call return method that is activated before an entity is updated.

Spring Security

Spring Security is the Spring module responsible for providing security to the application. It takes care of both authentication and authorization, as well as protecting against common errors.

The main annotations are:

  • @EnableWebSecurity - enable security resources.
  • @EnableAuthorizationServer - enables the AuthorizationServer.
  • @EnableResourceServer – allows the application to behave like a Resource Server.
  • @EnableGlobalMethodSecurity – activates global method security.
  • @Secured – is used to specify a list of functions in a method.
  • @PreAuthorize – provides express-based access control.
  • @PreFilter – filters a collection argument before executing the method, defining refined security rules using Spring EL. The filter is applied to a list that is being passed as an input parameter to the annotated method.
  • @PosFilter – filters lists of objects based on the custom security rules that we define, ou seja, defines to filter the return list of a method applying that rule to all the elements of the list. If the value is authenticated, the item will be kept on the list, otherwise the item will be removed.
  • @AuthenticationPrincipal – indicates Spring to insert the user logged into the application.

Spring Cache

The Spring Cache is a Spring Framework module designed for data caching, in other words, it allows us to temporarily store results of expensive operations (such as database queries, calls to external APIs, or heavy calculations) to avoid unnecessary recomputations and improve application performance. This module:

  • We can improve performance by reducing the response time of methods that return the same given frequency.
  • Reduce the load on external services or data repositories.
  • Simplify caching implementation using declarative annotations instead of manual logic.

The main annotations are:

  • @EnableCaching - enables or supports non-Spring caching. It must be placed in a configuration class.
  • @Cacheable - indicates that the result of a method must be cached.
  • @CachePut - force the method to be executed and update the cache with the new result, regardless of whether there is anything in the cache.
  • @CacheEvit - remove cache entries (very useful for operations that alter the state of two dice.
  • @Caching - groups multiple annotations.

Spring Cloud

The Spring Cloud is a Spring ecosystem project that provides tools to build distributed, resilient and scaled systems, especially intended for architectures based on microservices.

It was designed to facilitate the development of applications that require addressing challenges such as service discovery, load balancing, centralized configuration, circuit breakers, API gateway, messaging, among others.

O Spring Cloud solves several common technical challenges of distributed systems:

  • Discover and register services (with Spring Cloud Netflix Eureka).
  • Load balancing (with Spring Cloud LoadBalancer or Ribbon).
  • Centralized configuration (with Spring Cloud Config).
  • Circuit Breaker / Fault tolerance (com Resilience4j ou Hystrix).
  • Routing and Gateway (with Spring Cloud Gateway).
  • Distributed messaging (with Spring Cloud Stream).
  • Distributed monitoring and tracking (with Sleuth + Zipkin).
  • Security in microservices (with OAuth2, via Spring Cloud Security).
  • Event bus for configuration updates (with Spring Cloud Bus).
  • etc

It is made up of several sub modules. Right now, you won't be able to set which module which annotation belongs to, but it's also not difficult to find which module it belongs to (name-I know you need to add the starter with pom.xml if you're using Apache Maven). To help nisso, follow the official documentation.

The main annotations are:

  • @EnableConfigServer - active or centralized and remote configuration server.
  • @RefreshScope - allows you to reload beans with new configurations without the need to reinitialize the application.
  • @EnableEurekaServer - active or Eureka server.
  • @EnableEurekaClient - register the service in Eureka.
  • @EnableFeignClients - enables Feign clients.
  • @FeignClient - defines a declarative HTTP client.
  • @EnableDiscoveryClient - allows the app to register and discover services.
  • @RefreshScope - allows reloading properties like /actuator/refresh.
  • @LoadBalanced - insert a RestTemplate with load balancing inlay.
  • @EnableCircuitBreaker - activate circuit breaker methods.
  • @Headers - defines default headers for the Feign Client.
  • @CircuitBreaker - apply circuit breaker (Resilience4j library) to a method.
  • @RateLimiter - applies rate limiting.
  • @Bulkhead - check consistency for critical methods.

And many, many other annotations…

Spring Validation

The main objective of Spring Validation is to ensure that the input data is correct and consistent before being processed for the application. Isso avoids logic problems, unexpected exceptions, persistence of invalid data, among others.

The main annotations are:

  • @Valid - performs object validation. The class attributes need to be annotated with validation annotations, such as @NotBlank, @NotNull, @NotEmpty, etc.
  • @Validated - enables validation in Spring methods/classes.
  • @NotNull, @Size, @Email, etc - bean validation annotations (javax.validation).
  • @Pattern - validation with regex.
  • @Positive and @Negative - validation for positive or negative values.

And many, many other annotations…

Spring Scheduling

Spring Scheduling is a Spring Framework module that allows you to schedule tasks for automatic execution on defined schedules or intervals. It is often used in applications that need to execute recurring processes, such as sending emails, generating reports, synchronizing data, etc.

The main annotations are:

  • @EnableScheduling - activates the execution of scheduled tasks.
  • @Scheduled - indicates that the method must be executed on a schedule. It can be used with various attributes.
  • @EnableAsync – when actions are required in the system in the background (another thread). This annotation must be placed in classes annotated with @Configuration, so that Spring enables and supports asynchronous execution.
  • @Async – Enable or use the execution of asynchronous methods with @EnableAsync, check any method of a managed bean. As such method is invoked, Spring will guarantee that its execution will be in another thread.

Spring Batch

Spring Batch is a Spring framework focused on batch processing. It provides tools and abstractions to process large volumes of data efficiently, safely and with robust monitoring. We use him to:

  • Process large volumes of transactional data automatically and at scale.
  • Execute scheduled tasks
  • Guarantee reprocessing in case of failure (transactions with commit/rollback, retention).

The main annotations are:

  • @EnableBatchProcessing - activate or support Spring Batch.
  • @BeforeStep and @AfterStep - execute methods before/after a Step.
  • @BeforeJob and @AfterJob - execute methods before/after a Job.

Spring AMQP (RabbitMQ)

Spring AMQP is a Spring ecosystem module designed to facilitate asynchronous and decoupled communication between systems using AMQP (Advanced Message Queuing Protocol), with native support for RabbitMQ — the message broker most used with this protocol.

Spring AMQP abstracts the complexity of communication with AMQP brokers, offering a more object-oriented and friendly Spring-style programming. It allows applications to produce and consume messages with RabbitMQ, naturally integrating with the functionalities already built in Spring, such as dependency injection, annotation configuration and event management.

The main annotations are:

  • @EnableRabbit - enable detection of RabbitMQ listeners in Spring context.
  • @RabbitListener - listen to messages from a specific row.

Spring WebSocket

Spring WebSocket provides support for real-time, two-way communication between client and server using the WebSocket protocol, as well as providing fallback for STOMP over WebSocket using SockJS when WebSocket is not available.

The main annotations are:

  • @EnableWebSocket - activates WebSocket support.
  • @ServerEndpoint - defines a WebSocket endpoint.
  • @EnableWebSocketMessageBroker - enable or support WebSocket with STOMP.
  • @MessageMapping - map STOMP messages sent for that destination.
  • @SendTo - defines where the response should be sent.
  • @SendToUser - send messages directly to a specific user.
  • @Payload - mark or content of the message.
  • @DestinationVariable - extract variables from the STOMP URL.
  • @Header - captures custom message headers.

Spring Retry

Spring Retry is a complementary module for the Spring ecosystem that provides an easy way to add automatic retries to operations that may be temporarily missing, such as API calls, data bank connections, or network operations. It adds resilience to the application.

The main annotations are:

  • @EnableRetry - activate or support Spring Retry in the project.
  • @Retryable - marks a method so that it is executed again in case of failure.
  • @Recover - defines the method that will be called if all failed attempts are made.
  • @Backoff - is used in conjunction with the @Retryable annotation. This annotation defines a waiting strategy (delay) between attempts. When an exception occurs and the method is reexecuted, @Backoff determines how long to wait before trying again — the so-called backoff interval.

Spring AOP

Spring AOP (Aspect-Oriented Programming) is two modules of the Spring Framework that allows you to separate transversal logic (cross-cutting concerns) from the main business code. In other words, with AOP we can modularize behaviors that are only repeated in several parts of the application, such as:

  • Logging.
  • Authentication/authorization.
  • Transactions.
  • Handling of excesses.
  • Metrics and monitoring.

The main annotations are:

  • @Aspect - declare a class as an Aspect (an advice container).
  • @Before - execute the advice before the next method.
  • @After - execute the advice after the next method (independent of the event).
  • @AfterReturning - executes the advice after or returns after a method.
  • @AfterThrowing - execute the advice case or method throw exception.
  • @Around - wraps the method completely (full control gives execution).
  • @Pointcut - define a reused expression to identify intercepted methods.

Conclusion

Whew!! Gee! It was a lot of work and effort that I made to leave everything summarized and complete, but you knew that Spring and its modules are the most that I can address in this article. Much more... It is worth it to continue your search in perfecting your knowledge about it. I hope to contribute to building your knowledge and please feel free to contact me on LinkedIn, if desired.

My linkedin: https://www.linkedin.com/in/pablo-cavalcante/

Good studies! See you later!

Top comments (0)