In the @PostConstruct doc it says about the annotated methods:
"The method MUST NOT throw a checked exception."
How would one deal with e.g. an IOException which can be thrown in such a method? Just wrap it in a RuntimeException and let the user worry about the faulty initial state of the object? Or is @PostConstruct the wrong place to validate and initialize objects which got their dependencies injected?
Annotation Type PostConstruct The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service.
When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.
Methods marked with the @PostConstruct will be invoked after the bean has been created, dependencies have been injected, all managed properties are set, and before the bean is actually set into scope.
In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.
Yes, wrap it in a runtime exception. Preferebly something more concrete like IllegalStateException
.
Note that if the init method fails, normally the application won't start.
Generally, if you want or expect application start-up failure when one of your beans throws an exception you can use Lombok's @SneakyThrows
.
It is incredibly useful and succinct when used correctly:
@SneakyThrows @PostConstruct public void init() { // I usually throw a checked exception }
There's a recent write-up discussing its pros and cons here: Prefer Lombok’s @SneakyThrows to rethrowing checked exceptions as RuntimeExceptions
Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With