【问题标题】:How to listen to entity creation when invoked programmatically?以编程方式调用时如何监听实体创建?
【发布时间】:2018-08-02 17:35:22
【问题描述】:

我有一个(下面简化的)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 调用时才有效。意思是,以编程方式调用时不起作用。

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

【问题讨论】:

  • 你在用mongo吗?

标签: spring-boot events event-handling crud


【解决方案1】:
  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() {}
    .......
    

你可以在你的实体类中使用它

【讨论】:

    【解决方案2】:

    使用 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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多