簡體   English   中英

我們可以將 spring 原型 bean 與 try-with-resources 一起使用嗎?

[英]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 的回調方法。

每點解釋:

  1. try-with-resources :它是一種語法糖(Java 1.7 或更高版本),用於:
    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

  1. destroyMethod它是一個回調方法,spring 讓您實現,在實例被容器銷毀之前調用: https://docs.Z2A2D595E6ED9A0B24F027F2B63B134D6豆類工廠性質

但,

對於原型 bean,Spring 不管理其完整的生命周期; 無論 scope 是什么,都會在所有對象上調用初始化生命周期回調方法,在原型的情況下,不會調用配置的銷毀生命周期回調。

參考: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-scopes-prototype

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM