DTO Mirror is a utility library for Spring Boot that simplifies the creation and transformation of DTOs from entities. It helps ensure secure and flexible data transfer in API responses by automating field exclusion and data mapping.
@ExcludeFields
and @MapField
.The @ExcludeFields
annotation allows you to exclude specific fields from the response DTO. It is applied to methods within classes annotated with @RestController
or @Controller
.
Example:
@ExcludeFields({"id"})
@GetMapping("users/{id}")
public Person getPerson(@PathVariable String id) {
return repository.findById(id);
}
In this example, the id field will be excluded from the Person object in the API response by setting it to null.
The @MapField
annotation enables dynamic transformation of field values using SpEL (Spring Expression Language) expressions. It can be applied to fields within entities or DTO classes.
public class User {
@MapField(expression = "fullName?.toUpperCase()")
private String fullName;
@MapField(
expression = "fullName?.split(' ')?.length > 0 ? fullName?.split(' ')[0]?.toLowerCase() : null")
private String username;
// Getters and setters
}
Combined Example:
@RestController
@DTOProcessor
@RequestMapping("/api/")
public class ExampleController {
@ExcludeFields(value = {"city"})
@GetMapping("users")
public User getUser() {
User user = new User();
user.setFullName("Murilo Alves");
user.setCity("São Paulo");
return user;
}
}
public class User {
@MapField(expression = "fullName?.toUpperCase()")
private String fullName;
@MapField(
expression =
"fullName?.split(' ')?.length > 0 ? fullName?.split(' ')[0]?.toLowerCase() : null")
private String username;
private String city;
// Getters and setters
}
To use DTO Mirror in your Spring Boot project, add the following dependency:
<dependency>
<groupId>io.github.muriloalvesdev</groupId>
<artifactId>dto-mirror</artifactId>
<version>1.0.0</version>
</dependency>
@ExcludeFields
.@MapField
.Simplify and secure your API data handling with DTO Mirror!