如何以编程方式调用实体创建?

时间:2018-02-22 18:24:13

标签: spring-boot events event-handling crud

我有一个(简化如下)RestController调用CrudRepository。

@RestController
@RequestMapping({"/carApi"})
public class RestService {
    @Autowired
    private StorageService storageService;

    @PostMapping
    public RightTriangle create(@RequestBody DegregatedCar degregatedCar) {
        // Some logic
        Car car = convert(degregatedCar);
        return storageService.save(car);
    }
}

public interface StorageService extends CrudRepository<Car, Long> {
}

我想在保存实体(在这种情况下是汽车)之后做一些额外的事情。

我尝试使用@RepositoryEventHandlerAbstractRepositoryEventListener,但正如所述here,这些仅在CrudRepository公开的REST调用时有效。意思是,在以编程方式调用时不起作用。

知道如何监听存储库事件,无论它们是如何被调用的?

2 个答案:

答案 0 :(得分:0)

  1. 如果您使用的是Mongo(spring-data-mongodb),则可以使用Mongo Lifecycle Events。例如

    @Component
    public class MongoListener extends AbstractMongoEventListener<YourEntity>
    {
    
       @Override
       public void onAfterSave(AfterSaveEvent<YourEntity> event) {
          // Your logic here.       
        }
      }
    //There are many other methods in AbstractMongoEventListener like onBeforeSave ......
    }
    
  2. 如果您正在使用spring-data-jpa的任何关系数据库,则可以使用JPA生命周期事件,如

    @PrePersist void onPrePersist() {}
    @PostPersist void onPostPersist() {}
    .......
    
  3. 您可以在实体类

    中使用它

答案 1 :(得分:0)

使用AOP解决它。例如:

@Aspect
@Component
public class SystemLoggerService {
    @Around("execution(* com.whatever.StorageService.save(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        // TODO: Handle saving multiple save methods.
        // TODO: Log after transaction is finished.
        Car car = (Car) joinPoint.getArgs()[0];
        boolean isCreated = car.id == null;
        joinPoint.proceed();
        if (isCreated) {
            LOGGER.info("Car created: " + car);
        } else {
            LOGGER.info("Car saved: " + car);
        }
    }
}