Want to know if we can use spring prototype bean with try-with-resources mechanism:
MyResource
implements AutoCloseable
Suppose I have a bean defined as:
@Configuration
public class ResourceCreation {
@Bean()
@Scope("prototype")
public MyResource createResource() {
return new MyResource("Test");
}
}
I have a factory class to generate the prototype beans:
public class ResourceFactory() {
@Autowired
ApplicationContext m_applicationContext;
public static generateResource() {
return m_applicationContext.getBean(MyResource.Class);
}
}
Then to use try-with-resources:
try (MyResource = ResourceFactory.generateResource()) {
...
}
So in this way, is there any problem? Because spring container should manage the lifecycle of the prototype bean. Will the close()
method in the MyResource
gets called after the try block ends?
Short answer : Yes thanks to try-with-resources.
Long answer :
These two are completely unrelated concepts. You are mixing try-with-resources (1) which is a java concept and the destroyMethod (2), a callback method of a spring managed bean.
Explaining per point:
MyResource myResource = ResourceFactory.generateResource();
try {
...
} finally {
myResource.close();
}
and it will be called for any class that implements java.lang.AutoCloseable
or java.io.Closeable
interface.
Reference: https://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
But,
In case of a prototype bean, Spring does not manage his complete lifecycle; initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.