SpringBoot项目使用SpringDataJpa提供的审计功能的使用流程

SpringDataJpa提供审计注解:@CreatedBy,@LastModifiedBy,@CreatedDate,@LastModifiedDate

第一步:在SpringBoot启动类上添加@EnableJpaAuditing

public @interface EnableJpaAuditing {

    /**
     * Configures the {@link AuditorAware} bean to be used to lookup the current principal.
     *
     * @return
     */
        // 当SpringIOC容器中注册了多个审计的Bean,需要指定Bean的名称
    String auditorAwareRef() default "";

    /**
     * Configures whether the creation and modification dates are set. Defaults to {@literal true}.
     *
     * @return
     */
    boolean setDates() default true;

    /**
     * Configures whether the entity shall be marked as modified on creation. Defaults to {@literal true}.
     *
     * @return
     */
    boolean modifyOnCreate() default true;

    /**
     * Configures a {@link DateTimeProvider} bean name that allows customizing the {@link org.joda.time.DateTime} to be
     * used for setting creation and modification dates.
     *
     * @return
     */
    String dateTimeProviderRef() default "";
}

原文:

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.

翻译:

如果将AuditorAware类型的bean公开给ApplicationContext,则审计基础结构会自动选择它并使用它来确定要在域类型上设置的当前用户。 如果在ApplicationContext中注册了多个实现,则可以通过显式设置@EnableJpaAuditing的auditorAwareRef属性来选择要使用的实现。

第二步:在实体类上进行添加注解的标注字段

class Customer {

  @CreatedBy
  private User user;

  @CreatedDate
  private DateTime createdDate;

  // … further properties omitted
}

View Code

第三步:实现 AuditorAware 接口,泛型T是返回的限定类型,并注册到Spring管理的容器中

class SpringSecurityAuditorAware implements AuditorAware<User> {

  public Optional<User> getCurrentAuditor() {

    return Optional.ofNullable(SecurityContextHolder.getContext())
              .map(SecurityContext::getAuthentication)
              .filter(Authentication::isAuthenticated)
              .map(Authentication::getPrincipal)
              .map(User.class::cast);
  }
}

View Code

第四步:在实体类上添加 @EntityListeners(AuditingEntityListener.class) 注解

之后,当进行save操作的时候,会自动设置获取通过审计注解获取的相关信息

参考官方文献:https://docs.spring.io/spring-data/jpa/docs/2.1.9.RELEASE/reference/html/

复制请注明出处,在世界中挣扎的灰太狼