JPA Auditing
General Auditing Configuration
Spring Data JPA ships with an entity listener that can be used to trigger the capturing of auditing information. First, you must register the AuditingEntityListener
to be used for all entities in your persistence contexts inside your orm.xml
file, as shown in the following example:
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="….data.jpa.domain.support.AuditingEntityListener" />
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
You can also enable the AuditingEntityListener
on a per-entity basis by using the @EntityListeners
annotation, as follows:
@Entity
@EntityListeners(AuditingEntityListener.class)
public class MyEntity {
}
The auditing feature requires spring-aspects.jar to be on the classpath.
|
With orm.xml
suitably modified and spring-aspects.jar
on the classpath, activating auditing functionality is a matter of adding the Spring Data JPA auditing
namespace element to your configuration, as follows:
<jpa:auditing auditor-aware-ref="yourAuditorAwareBean" />
As of Spring Data JPA 1.5, you can enable auditing by annotating a configuration class with the @EnableJpaAuditing
annotation. You must still modify the orm.xml
file and have spring-aspects.jar
on the classpath. The following example shows how to use the @EnableJpaAuditing
annotation:
@Configuration
@EnableJpaAuditing
class Config {
@Bean
public AuditorAware<AuditableUser> auditorProvider() {
return new AuditorAwareImpl();
}
}
If you expose a bean of type AuditorAware
to the ApplicationContext
, the auditing infrastructure automatically picks it up and uses it to determine the current user to be set on domain types. If you have multiple implementations registered in the ApplicationContext
, you can select the one to be used by explicitly setting the auditorAwareRef
attribute of @EnableJpaAuditing
.