@ PostConstruct & Checked excepciones


En el documento @PostConstruct dice sobre los métodos anotados:

"El método NO DEBE lanzar una excepción marcada."

¿Cómo se trataría, por ejemplo, una excepción IOException que se puede lanzar en dicho método? Simplemente envuélvalo en una RuntimeException y deje que el usuario se preocupe por el estado inicial defectuoso del objeto. ¿O es @PostConstruct el lugar equivocado para validar e inicializar objetos que recibieron sus dependencias inyectadas?

Author: skaffman, 2012-01-05

3 answers

Sí, envuélvalo en una excepción de tiempo de ejecución. Preferencialmente algo más concreto como IllegalStateException.

Tenga en cuenta que si el método init falla, normalmente la aplicación no se iniciará.

 37
Author: Bozho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-05 09:40:17

Use una excepción suavizada como esta, en efecto envolviendo en RuntimeException: https://repl.it/@djangofan/SoftenExceptionjava

private static RuntimeException softenException(Exception e) {
    return checkednessRemover(e);
}
private static <T extends Exception> T checkednessRemover(Exception e) throws T {
    throw (T) e;
}

Entonces el uso es como:

} catch (IOException e) {
        throw softenException(e);
        //throw e; // this would require declaring 'throws IOException'
}
 0
Author: djangofan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-21 21:28:34

Generalmente, si desea o espera un fallo en el inicio de la aplicación cuando uno de sus frijoles arroja una excepción, puede usar el @SneakyThrows de Lombok.

Es increíblemente útil y sucinto cuando se usa correctamente:

@SneakyThrows
@PostConstruct
public void init() {
    // I usually throw a checked exception
}

Hay un artículo reciente discutiendo sus pros y contras aquí: Prefiero @SneakyThrows de Lombok a repensar las excepciones verificadas como RuntimeExceptions

Disfrute!

 0
Author: wild_nothing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-11 21:17:03