@PostConstruct&Checked例外

在@PostConstruct文档中,它描述了带注释的方法:

“该方法绝不能抛出已检查的exception。”

如何处理例如可以在这种方法中抛出的IOException? 只需将它包装在RuntimeException中,让用户担心对象的错误初始状态? 或者@PostConstruct是错误的地方来validation和初始化注入了依赖项的对象?

是的,将其包装在运行时exception中。 优选更具体的东西,如IllegalStateException

请注意,如果init方法失败,通常应用程序将无法启动。

使用像这样的软化exception,实际包装在RuntimeException中: https : //repl.it/@djangofan/SoftenExceptionjava

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

用法如下:

 } catch (IOException e) { throw softenException(e); //throw e; // this would require declaring 'throws IOException' } 

通常,如果您希望或期望应用程序启动失败,当您的某个bean抛出exception时,您可以使用Lombok的@SneakyThrows

正确使用它非常有用且简洁:

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

最近有一篇文章讨论了它的优点和缺点: 首选Lombok的@SneakyThrows重新抛出已检查的exception作为RuntimeExceptions

请享用!