DATAJDBC-390 - Add ordering to RelationalAuditingEventListener to run before other listeners without explicitly specified order.

When an event listener is used to set an id before saving it, this ensures the auditing happens before setting the id.
If this is not ensured the auditing listener doesn't consider the entity as new and doesn't set created date and created by user.

Original pull request: #159.
This commit is contained in:
Jens Schauder
2019-07-09 12:00:52 +02:00
committed by Mark Paluch
parent c1e460bd9f
commit 7089e077d5
2 changed files with 53 additions and 3 deletions

View File

@@ -28,6 +28,7 @@ import java.util.function.Consumer;
import org.assertj.core.api.SoftAssertions;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -41,7 +42,9 @@ import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.relational.core.mapping.NamingStrategy;
import org.springframework.data.relational.core.mapping.event.BeforeSaveEvent;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ActiveProfiles;
/**
@@ -176,6 +179,23 @@ public class EnableJdbcAuditingHsqlIntegrationTests {
});
}
@Test // DATAJDBC-390
public void auditingListenerTriggersBeforeDefaultListener() {
configureRepositoryWith( //
AuditingAnnotatedDummyEntityRepository.class, //
TestConfiguration.class, //
AuditingConfiguration.class, //
OrderAssertingEventListener.class) //
.accept(repository -> {
AuditingAnnotatedDummyEntity entity = repository.save(new AuditingAnnotatedDummyEntity());
assertThat(entity.id).isNotNull();
});
}
/**
* Usage looks like this:
* <p>
@@ -296,4 +316,20 @@ public class EnableJdbcAuditingHsqlIntegrationTests {
return () -> Optional.of("user");
}
}
/**
* An event listener asserting that it is running after {@link AuditingConfiguration#auditorAware()} was invoked and
* set the auditing data.
*/
@Component
static class OrderAssertingEventListener implements ApplicationListener<BeforeSaveEvent> {
@Override
public void onApplicationEvent(BeforeSaveEvent event) {
Object entity = event.getEntity();
assertThat(entity).isInstanceOf(AuditingAnnotatedDummyEntity.class);
assertThat(((AuditingAnnotatedDummyEntity) entity).createdDate).isNotNull();
}
}
}