For most of Spring developers, I think you are familiar with the simple auditing features in Spring Data project, but in the past years, it only works with the blocking APIs. The long-awaited Reactive AuditorAware supportwill be available in the new Spring Data release train.

This is the 4th post of the R2dbc series:

Let’s create a new Spring Boot project to experience the auditing feature.

Open your browser and navigate to Spring Intializr page.

  • Build tools: choose Maven as build tools
  • Java version, choose the latest Java 11 or above
  • Spring boot version: choose Spring Boot 2.4.0-M3 to get the newest ReactiveAuditorAware support
  • And add the following dependencies to the project.
  • Reactive Web
  • Spring Data R2dbc
  • Security
  • Lombok

Enabling Auditing Support

Add @EnableR2dbcAuditing annotation on the configuration class.

@Configuration
@EnableR2dbcAuditing
class DatabaseConfig{

}

Declare a ReactiveAuditorAware bean. When a ReactiveAuditorAware bean is available, it will fill the fields annotated by @CreatedBy and @LastModifiedBy annotations automatically in the entity classes.

@Bean
ReactiveAuditorAware<String> auditorAware() {
    return () -> ReactiveSecurityContextHolder.getContext()
        .map(SecurityContext::getAuthentication)
        .filter(Authentication::isAuthenticated)
        .map(Authentication::getPrincipal)
        .map(User.class::cast)
        .map(User::getUsername);
}

In the above example, we will read the username from Spring SecurityContext. We will introduce the Spring Security configuration later.

#r2dbc #spring-boot #postgres #spring-data #spring-data-r2dbc

Data Auditing With Spring Data R2dbc
22.50 GEEK