Sample Code of the AuditorAware audit function based on Spring Data,

Source: Internet
Author: User

Sample Code of the AuditorAware audit function based on Spring Data,

Spring Data provides the audit function: when the entity is created or modified. Spring Data allows you to add @ CreatedBy, @ LastModifiedBy, @ CreatedDate, @ LastModifiedDate annotations to the attributes of the object class, and configure corresponding configuration items to implement the audit function, the system automatically records the values of the four attributes createdBy CreatedDate lastModifiedBy lastModifiedDate. The specific configuration items are as follows.

Example

Create an object class

package com.hfcsbc.infrastructureservice.domain;import com.hfcsbc.repository.support.domain.AbstractAuditingEntity;import lombok.Data;import org.springframework.data.annotation.CreatedBy;import org.springframework.data.annotation.CreatedDate;import org.springframework.data.annotation.LastModifiedBy;import org.springframework.data.annotation.LastModifiedDate;import org.springframework.data.jpa.domain.support.AuditingEntityListener;import javax.persistence.*;import java.util.Date;/** * Create by pengchao on 2018/3/7 */@Entity@Data@EntityListeners({AuditingEntityListener.class})public class Person {  @Id  @GeneratedValue  private Long id;  private String name;  private Integer age;  @CreatedBy  @Column(      name = "created_by",      nullable = false,      length = 50,      updatable = false  )  private String createdBy;  @CreatedDate  @Column(      name = "created_date",      nullable = false,      updatable = false  )  private Date createdDate = new Date();  @LastModifiedBy  @Column(      name = "last_modified_by",      length = 50  )  private String lastModifiedBy;  @LastModifiedDate  @Column(      name = "last_modified_date"  )  private Date lastModifiedDate = new Date();}

Create a Repository

package com.hfcsbc.repository;import com.hfcsbc.domain.Person;import org.springframework.data.jpa.repository.JpaRepository;/** * Create by pengchao on 2018/3/7 */public interface PersonRepository extends JpaRepository<Person, Long> {}

Configure bean for getting user information

package com.hfcsbc.infrastructureservice.config;import org.springframework.data.domain.AuditorAware;import org.springframework.security.core.Authentication;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.stereotype.Component;import java.util.Optional;/** * Create by pengchao on 2018/3/7 */@Component("auditorAware")public class AuditorAwareImpl implements AuditorAware<String> {  @Override  public Optional<String> getCurrentAuditor() {    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();    return Optional.of(authentication.getPrincipal().toString());  }}

Enable audit in Spring Boot Portal

package com.hfcsbc.infrastructureservice;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.data.jpa.repository.config.EnableJpaAuditing;import org.springframework.scheduling.annotation.EnableAsync;@SpringBootApplication@EnableJpaAuditing(auditorAwareRef = "auditorAware")@EnableAsyncpublic class PersonApplication {    public static void main(String[] args) {    SpringApplication.run(PersonApplication.class, args);  }}

The configuration is complete. When you use repository to save an object, createdBy CreatedDate lastModifiedBy lastModifiedDate is automatically inserted with the audit function.

Note: how to obtain user information in asynchronous Methods

Because repository is used in the Asynchronous Method to save objects and user information cannot be obtained, you need to add the following configuration items to obtain user information in Authentication.

package com.hfcsbc.config;import org.springframework.beans.factory.config.MethodInvokingFactoryBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.core.context.SecurityContextHolder;/** * Create by pengchao on 2018/3/7 */@Configurationpublic class AuditorAwareConfig {  @Bean  public MethodInvokingFactoryBean methodInvokingFactoryBean() {    MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();    methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class);    methodInvokingFactoryBean.setTargetMethod("setStrategyName");    methodInvokingFactoryBean.setArguments(new String[]{SecurityContextHolder.MODE_INHERITABLETHREADLOCAL});    return methodInvokingFactoryBean;  }}

The main function of SecurityContextHolder is to associate the currently executed process with SecurityContext.

SecurityContextHolder. MODE_INHERITABLETHREADLOCAL: used to integrate the SecurityContextHolder of the parent thread into a thread with a parent-child relationship;

SecurityContextHolder. MODE_INHERITABLETHREADLOCAL: globally shared SecurityContextHolder.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.