简体   繁体   中英

Can we use spring prototype bean together with try-with-resources?

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:

  1. try-with-resources : it's a syntactic sugar (Java 1.7 or later) for:
    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

  1. destroyMethod it's a callback method, that spring lets you implement, called before the instance is destroyed by the container as per: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-nature

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM