Managing exit code after context initialization exception

Viewed 43

I would like to know if there is any way to set the returned exit code after a BeanCreationException occured during the Spring initialization.

So far the only solution that I have found is to wrap the entire application inside a try/catch, and call System.exit after the block :

    public static int runForExitCode (String[] args) {
        try {
            return SpringApplication.exit(SpringApplication.run(MyApplication.class, args));

        } catch (Exception e) {
            return extractExitCodeFrom(e) ;
        }
    }

This solution works as expected, but it makes me work out of Spring container, and adds an entire layer of complexity to my application, making the tests much more difficult to write...
For this reason, I would like to use a Spring-provided tool to manage the exit code.

I know there are some beans that can be implemented to handle the exit code : ExitCodeGenerator and ExitCodeExceptionMapper, but I have not been able to make them work after an exception that comes during context initialization, such as BeanCreationException.

Because the initialization is the time during which beans are created, I understand that I need a special way to handle the exceptions. I would have expected to find some property to be declared in the spring.factories file, but the closest tool that I found was the FailureAnalyzer interface, which only allows one to describe the exception with words.

I know that one might avoid the problem by moving the dangerous code from the bean declaration into the ApplicationRunner method, but I cannot proceed this way : I am trying to handle the possible Database exceptions, that might occur during a Spring Batch application initialization.

I may be missing some Spring dedicated feature, or thinking the wrong way. Maybe the try/catch block is the only solution to be kept ?

Thank you for your time,

Arturito

0 Answers
Related