SpringDataJpa使用审计(Auditing)功能
SpringBoot項(xiàng)目使用SpringDataJpa提供的審計(jì)功能的使用流程
SpringDataJpa提供審計(jì)注解:@CreatedBy,@LastModifiedBy,@CreatedDate,@LastModifiedDate
第一步:在SpringBoot啟動(dòng)類上添加@EnableJpaAuditing
public @interface EnableJpaAuditing {
/**
* Configures the {@link AuditorAware} bean to be used to lookup the current principal.
*
* @return
*/
// 當(dāng)SpringIOC容器中注冊(cè)了多個(gè)審計(jì)的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公開(kāi)給ApplicationContext,則審計(jì)基礎(chǔ)結(jié)構(gòu)會(huì)自動(dòng)選擇它并使用它來(lái)確定要在域類型上設(shè)置的當(dāng)前用戶。 如果在ApplicationContext中注冊(cè)了多個(gè)實(shí)現(xiàn),則可以通過(guò)顯式設(shè)置@EnableJpaAuditing的auditorAwareRef屬性來(lái)選擇要使用的實(shí)現(xiàn)。
第二步:在實(shí)體類上進(jìn)行添加注解的標(biāo)注字段
class Customer {
@CreatedBy
private User user;
@CreatedDate
private DateTime createdDate;
// … further properties omitted
}
View Code
第三步:實(shí)現(xiàn) AuditorAware 接口,泛型T是返回的限定類型,并注冊(cè)到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
第四步:在實(shí)體類上添加@EntityListeners(AuditingEntityListener.class) 注解
之后,當(dāng)進(jìn)行save操作的時(shí)候,會(huì)自動(dòng)設(shè)置獲取通過(guò)審計(jì)注解獲取的相關(guān)信息
參考官方文獻(xiàn):https://docs.spring.io/spring-data/jpa/docs/2.1.9.RELEASE/reference/html/
復(fù)制請(qǐng)注明出處,在世界中掙扎的灰太狼
總結(jié)
以上是生活随笔為你收集整理的SpringDataJpa使用审计(Auditing)功能的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何使用工具对SAP CRM系统的oda
- 下一篇: 原神好兆头任务五个征兆是什么 五个征兆怎