@PostConstruct&检查异常
在 @PostConstruct 文档中,它说注释方法:
In the @PostConstruct doc it says about the annotated methods:
该方法不得抛出被检查的异常。
如何处理例如一个IOException可以抛出这样的方法?只需将它包装在RuntimeException中,让用户担心对象的初始状态有问题?
或者是@PostConstruct错误的地方来验证和初始化注册的依赖关系的对象?
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?
是的,它在运行时异常中。预先说明一些更具体的东西,如 IllegalStateException
。
Yes, wrap it in a runtime exception. Preferebly something more concrete like IllegalStateException
.
请注意,如果init方法失败,通常应用程序将不会启动。
Note that if the init method fails, normally the application won't start.