SpringDataJpa使用審計(Auditing)功能


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/#auditing


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM