DEV Community

Pedro Henrique
Pedro Henrique

Posted on

## Working with Annotations in the Spring Framework: A Practical Guide

The Spring Framework is widely known for its simplicity and flexibility in developing Java applications. One of the fundamental aspects of Spring is the use of annotations to facilitate the creation of components, dependency management and application configuration.

In this article, we will explore some of the main Spring annotations and how they help in system development. We will also explain fundamental concepts such as Stateful and Stateless, and the role of the Controller and Service classes.

What are Annotations?

Annotations in Spring are represented by the @ symbol and are an example of the Dependency Injection Design Pattern. They allow you to define behaviors and configurations without having to write large amounts of boilerplate code. This makes development easier and makes the code cleaner and more organized.

Annotations in Spring

1. @Controller

The @Controller annotation is used in controller classes, whose main role is to receive HTTP requests (GET, POST, etc.) and send appropriate responses. The Controller serves as an entry point for requests made to the application.

2. @RestController

@RestController is a combination of two annotations:

  • @Controller: To receive requests.
  • @ResponseBody: Indicates that the return of each method will be the body of the HTTP response (JSON, XML, etc.).

This annotation simplifies the code by eliminating the need to use @ResponseBody in each method, making it easier to create REST APIs.

3. @Service

The @Service annotation is used to define service classes, which contain the business logic of the application. While the Controller only handles requests, the Service is responsible for processing them.

In addition, @Service works as a Spring bean, making it possible to perform dependency injection in other parts of the application.

4. @Component

The @Component annotation is more generic and can be applied to any class that needs to be managed by the Spring container. The main difference between @Component and @Service is that @Service is more semantic and is generally used for business logic classes, while @Component is used for more generic beans.

5. @Autowired

@Autowired is an annotation that allows dependency injection. It can be applied to fields, methods or constructors to indicate that Spring should resolve and inject the dependency automatically.

This annotation is widely used to reduce the need to manually instantiate objects. When applied to a class, Spring automatically searches for a compatible bean and injects it.

6. @Configuration

The @Configuration annotation indicates that the class contains methods that define beans or configurations that Spring should manage. It is often used in conjunction with @Bean to register beans from third-party classes, such as external libraries.

7. @bean

The @Bean is used to declare and register beans in the Spring container. It is especially useful when you need to manage the creation of objects that are not directly managed by Spring (such as classes from external libraries). The @Bean also ensures that the bean is created as a Singleton, that is, a single instance will be created and shared by the entire application.

Stateful vs Stateless

Stateful

In the Stateful context, the state of each client is maintained on the server. Imagine a login scenario, where the client enters their credentials. If they close the browser tab and reopen it again, they will still be logged in. This is because the server maintains the session state.

Stateless

In the Stateless scenario, the state is not maintained between requests. Each time the client makes a new request, it needs to provide all the necessary information (such as tokens or credentials) for the action to be performed. A common example are REST APIs, which work in a Stateless manner, requiring authentication for each request.

Other Important Notes and Concepts

1. @PathVariable

The @PathVariable is used to capture variables directly from the request URL and map them to the parameters of a method. For example:

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
// Code to fetch the user based on the ID provided in the URL
}
Enter fullscreen mode Exit fullscreen mode

In this example, the value of id in the URL /users/{id} will be captured and passed to the id parameter of the method.

2. @PostMapping

The @PostMapping is an annotation that indicates that the associated method should handle HTTP requests of the POST type. This type of request is commonly used to create new resources or send data to the server. Example:

PostMapping("/users")
public void criarUsuario(@RequestBody Usuario usuario) {
// Code to create a new user
}
Here, the method processes data sent by the request body (JSON, XML, etc.) and creates a new resource based on that data.

Summary:
@Controller: Receives HTTP requests and sends responses.
@RestController: Combines @Controller with @ResponseBody to create REST APIs.
@Service: Contains the application's business logic.
@Component: Generic annotation to manage beans in Spring.
@Autowired: Automatic dependency injection.
@Configuration: Defines a configuration class.
@bean: Registers a bean in the Spring container.
Stateful: The client's state is maintained on the server.
Stateless: Each request is independent and does not maintain state.
@PathVariable: Captures variables from the URL.
@PostMapping: Handles POST requests.
Conclusion:
Spring Framework annotations make development more productive and code cleaner and more efficient. With the correct use of annotations such as @Controller, @Service, @Autowired and @bean, it is possible to structure and organize the application in a modular and scalable way. In addition, understanding concepts such as Stateful and Stateless is crucial to developing safe and efficient systems.

Top comments (0)