Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PostConstruct & Checked exceptions

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?

like image 988
fasseg Avatar asked Jan 05 '12 09:01

fasseg


People also ask

What is @PostConstruct used for?

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.

What is @PostConstruct annotation in spring?

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.

When @PostConstruct is called in Java?

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.

Is @PostConstruct deprecated?

In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.


2 Answers

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.

like image 56
Bozho Avatar answered Sep 23 '22 21:09

Bozho


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!

like image 24
wild_nothing Avatar answered Sep 22 '22 21:09

wild_nothing