This question is an exact duplicate of:
Graceful handling of exception thrown while creating beans
I think you have a few options here, and which one is the best is largely down to personal preference and the structure of your application.
One option would be to perform all of the input validation before you call
SpringApplication.run(). This would work for any command line arguments, but would be cumbersome at best for anything configured via
Rather than throwing exceptions from your
@Bean methods, you could catch them and handle them appropriately. If the problem's minor you could log an info or warning message explaining the problem and allow the application to continue. If the problem's catastrophic, you could log an error message and then call
System.exit(). While this will provide user-friendly error reporting for any exceptions thrown while your
@Bean methods are being called, you'll still be left with stack traces for any exceptions that occur after that.
Lastly, you could wrap the call to
SpringApplication.run() in a try-catch block. You could then examine the caught exception and the chain of causes to determine an appropriate error message to log. The advantage of this approach is that it will let you provide a user-friendly error message for any exception that causes
SpringApplication.run() to fail, not just one that's thrown from within one of your
Assuming there are command-line arguments to validate, I would probably use a combination of the first and third options. For the first I'd use a CLI library such as JOpt Simple to make things a bit easier.