[英]Can we use spring prototype bean together with try-with-resources?
想知道我們是否可以使用帶有 try-with-resources 機制的 spring 原型 bean:
MyResource
實現AutoCloseable
假設我有一個 bean 定義為:
@Configuration
public class ResourceCreation {
@Bean()
@Scope("prototype")
public MyResource createResource() {
return new MyResource("Test");
}
}
我有一個工廠 class 來生成原型bean:
public class ResourceFactory() {
@Autowired
ApplicationContext m_applicationContext;
public static generateResource() {
return m_applicationContext.getBean(MyResource.Class);
}
}
然后使用 try-with-resources:
try (MyResource = ResourceFactory.generateResource()) {
...
}
那么這樣一來,有沒有問題呢? 因為 spring 容器應該管理原型 bean 的生命周期。 MyResource
中的close()
方法會在 try 塊結束后被調用嗎?
簡短的回答:是的,感謝 try-with-resources。
長答案:
這兩個是完全不相關的概念。 您正在混合try-with-resources (1) 這是一個 java 概念和destroyMethod (2),一個 spring 托管 bean 的回調方法。
每點解釋:
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.
參考: https://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
但,
對於原型 bean,Spring 不管理其完整的生命周期; 無論 scope 是什么,都會在所有對象上調用初始化生命周期回調方法,在原型的情況下,不會調用配置的銷毀生命周期回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.