Home > Blockchain >  Does AfterReturningAdvice start after of before Transaction closed?
Does AfterReturningAdvice start after of before Transaction closed?

Time:12-02

I am using BeanPostProcessor which is executing some code after my Service methods are done. But my Service is @Transactional also.

Is this "trigger" executes after of before end of Transaction in those methods?

@Component
public class MethodBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (findAnnotation(bean.getClass(), Service.class) != null) {
            var factory = new ProxyFactory(bean);
            factory.setProxyTargetClass(true);
            factory.addAdvice((AfterReturningAdvice) (returnValue, method, args, target) -> {
                if (method.isAnnotationPresent(Refreshable.class)) {
                    var refreshableDto = (RefreshableDto) returnValue;
                    if (refreshableDto != null) {
                        refreshableDto.copyId();
                    }
                }
            });
            factory.setExposeProxy(true);
            return factory.getProxy();
        }
        return bean;
    }

}

It is working fine so I could assume it works exactly after transaction but I am not sure. Is there are any place in docummentation or something where I can find that information?

CodePudding user response:

Remember the transaction in Spring is also implemented as an aspect and the transaction advice has a defined default order Ordered.LOWEST_PRECEDENCE. As the JavaDoc of Ordered says the lowest order value comes first:

The actual order can be interpreted as prioritization, with the first object (with the lowest order value) having the highest priority.

The information about the defined default order can be found in figure Table 2. Annotation-driven transaction settings of chapter 1.4.6. Using @Transactional (reference documentation of the 5.3.x version, other versions chaptering might differ, but the principle is the same).

You can change the order of the transactional AOP advice with two ways:

  • Annotation driven configuration: @EnableTransactionManagement(order = 123)
  • XML driven configuration: <tx:annotation-driven order="123"/>

The same your individual aspects defined with @Aspect beans can be further configured with @Order annotation.

  • Related