Cannot autowire service into implementation of AsyncUncaughtExceptionHandler

I have a problem with spring autowiring. I’ve got a class that implements AsyncUncaughtExceptionHandler.

@Component
public class MyExceptionHandler implements AsyncUncaughtExceptionHandler {

    @Autowired
    MyService myService;

    @Override
    public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
        if (throwable instanceof MyException) {
            myService.handleException((MyException) throwable);
        } else {
            //...
        }
    }

When the code runs into the places where myService is called, Nullpointer is thrown as myService is null. MyService is autowired on other places without any problem, only autowiring in the implementation of AsyncUncaughtExceptionHandler seems to cause issues.

@Service
public class MyService {

    public void handleException(MyException e) {
        //...
    }
}

I’ve been through some questions on StackOverflow, which solved similar problems. Those problems were caused by proxy mechanisms, but I did not manage to make the code work. Also, I am not sure if this is the problem.

Any help is appreciated. Thanks in advance.

Answer

Mistake was actually on my side in configuration of asyncExceptionHandler.

had to change this:

@Configuration
@EnableAsync
@ComponentScan
public class AsyncConfiguration implements AsyncConfigurer {

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new RccAsyncExceptionHandler();
    }
}

into this:

@Configuration
@EnableAsync
@ComponentScan
public class AsyncConfiguration implements AsyncConfigurer {

    @Autowired
    MyExceptionHandler rccAsyncExceptionHandler;

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return rccAsyncExceptionHandler;
    }
}

Rookie mistake, but I couldn’t find it for very long time.

Leave a Reply

Your email address will not be published. Required fields are marked *