Let's pretend that we have two Closeable
beans:
@Component
public class CloseableBean1 implements Closeable {
private BufferedOutputStream outputStream;
@Override
public void close() throws IOException {
try {
outputStream.close();
} catch (Exception e) {
// ignore e
}
}
}
@Component
public class CloseableBean2 implements Closeable {
@Autowired
private CloseableBean1 bean1;
@Override
public void close() throws IOException {
try {
bean1.close();
} catch (Exception e) {
// ignore e
}
}
}
Does Spring make sure that CloseableBean2
is closed first and then CloseableBean1
is closed?
There is nothing specific in documentation about order of disposing, but...
the description of depends-on
we can see, that depends-on
should be used only if bean does not explicitly depend on another. And there is noted, that dependent bean will always be destroyed first.
In your case bean CloseableBean2
always will be destroyed first, because it contains explicitly dependency of CloseableBean
.
I would prefer to make additional protection. Something like:
@Component
public class CloseableBean1 implements Closeable {
private boolean closed = false;
@Override
public void close() throws IOException {
if(closed) return;
outputStream.close();
closed=true;
}
}
Official documentation recommend us:
...and to internally mark the Closeable as closed, prior to throwing the IOException.
This approach helps to avoid accidental repeated call of close()
on already closed stream. But if exception will occurred during first invocation of close()
, we will able to handle it.
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