Search code examples
javaspringaopaspectjspring-aop

AfterThrowing advice, delegate to service


I have aop xml config like this:

    <aop:config>
        <aop:pointcut id="serviceMethod" expression="execution(* egovframework.example..impl.*Impl.*(..))" />

        <aop:aspect ref="exceptionTransfer">
            <aop:after-throwing throwing="exception" pointcut-ref="serviceMethod" method="transfer" />
        </aop:aspect>
    </aop:config>
    
    <bean id="exceptionTransfer" class="bla.bla.DefaultExceptionTransfer">
    </bean>

You can see that the line <aop:aspect ref="exceptionTransfer"> indicate that the aspect is linked with the bean below.

Now I want to convert this to java annotation based. What I have done:

@Configuration
@Aspect
public class ContextExceptionHandlerAspectConfiguration {

    @Pointcut("execution(* egovframework.example..impl.*Impl.*(..))")
    public void serviceAnnotation() { }

    //HOW TO WRITE AFTER THROWING
    
    @Bean
    public ExceptionTransfer exceptionTransfer() {
        return new DefaultExceptionTransfer();
    }
}

The problem is I don't know how to write the code to link the aspect with the exceptionTransfer. Please help, thanks


Solution

  • An example of how to achieve this is using @AfterThrowing as in the example below:

    @Slf4j
    @Aspect
    @Component
    public class LoggingAspect {
        @AfterThrowing(value = "execution(* com.amitph.spring.aop.service.FileSystemStorageService.readFile(..))",
                throwing = "ex")
        public void logAfterThrowing(JoinPoint joinPoint, Exception ex) {
    
            log.error("Target Method resulted into exception, message {}", ex.getMessage());
            notificationService.error(ex.getMessage());
        }
    }