First lets consider that we have CustomerRegister service that simply do its job.
@Service
class CustomerRegister {
private final CustomerRegister customerRegister;
CustomerRegister(CustomerRegister customerRegister) {
this.customerRegister = customerRegister;
}
@Transactional
public void create(Customer customer) {
customerRegister.persist(customer);
}
}
Later it was decided that it could be good to have a business metric about that registry operation. The common choice is to use org.springframework.boot.actuate.metrics.CounterService
Note that:
Using
@Transactional
, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating
If we decide to invoke
counterService.increment(REGISTY_METRIC);
within scope of create method then counter will be increased even in transaction was rollback.
My idea is to create an aspect that wraps that transactional proxy (which wrapping original CustomerRegister service). That @Aspect
component could then provides method annotated with @AfterReturning(pointcut =
that
increment metric counter.
Other words:
- How to implement aspect over another aspect?
- How to implement aspect over transactional proxy?