Video in progress
When several aspects (transaction, cache, your own logging aspect) apply to one method, how is their order determined?
Each advisor has an Ordered value: a smaller value means an outer layer, which runs first on the way in and last on the way out. You put @Order on your own aspect, and configure Spring's with @EnableTransactionManagement(order = ...) and @EnableCaching(order = ...).
📖 Answer
Inside the proxy the advisors work as a chain, like the layers of an onion. If the order isn't defined (equal order), the result isn't guaranteed.
By default the @Transactional and @Cacheable advisors are Ordered.LOWEST_PRECEDENCE, the innermost. Your own aspect is the same if it has no @Order.
When order matters:
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
class RetryAspect {
@Around("@annotation(retryable)")
Object retry(ProceedingJoinPoint pjp, Retryable retryable) throws Throwable {
for (int i = 1; ; i++) {
try {
return pjp.proceed();
} catch (TransientDataAccessException e) {
if (i >= retryable.attempts()) throw e;
}
}
}
}
- Retry and transaction: the retry must sit outside the transaction. Otherwise the retry happens inside that same rollback-only transaction and is useless. That's why the retry above got a smaller order.
- Cache and transaction: if the cache is on the outside, when the response comes from the cache no transaction is opened at all, which is good.
- A timing aspect: if it's outside, it also measures the commit time; if it's inside, it doesn't.
- Security: it's best for
@PreAuthorizeto be outermost, so no transaction is opened for a rejected request.
To check the order, the fastest way is to look at the proxy's advisors list in the debugger, or write logs in the aspects.
Sign up to mark studied questions and save your progress.