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
AuditorAwareto theApplicationContext, 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 theApplicationContext, you can select the one to be used by explicitly setting theauditorAwareRefattribute 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/
復制請注明出處,在世界中掙扎的灰太狼
總結
以上是生活随笔為你收集整理的SpringDataJpa使用审计(Auditing)功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何使用工具对SAP CRM系统的oda
- 下一篇: 后台OData model data查看