Search code examples
springdesign-patternsjavabeansdestroy

Disposal factory pattern in Spring?


I can use factory bean to create another beans in Spring. Is it also possible to dispose (destroy) of a bean by giving it to another one?

Fore example I have Database bean which serves as a factory for Corpus beans:

<bean id="Corpus" name="Corpus" factory-bean="Database"
    factory-method="loadCorpus">
</bean>

Upon loadCorpus, the database reads data from server and returns it as a corpus object.

Now I want to make some changes inside the corpus and put it back to database at the end of the program lifetime.

It would be logical to make this during the process of 'disposing' of corpus bean by giving it back to database for disposal.

But I see no configuration options for this. While creation can be set both with a bean and a method, the destroyment is only possible with a method.

How to reach my goal then?


Solution

  • Make your Database bean keep a reference to the Corpus instance it creates, and make it disposable. This way, when the container stops, the destroy method of the Database bean is called, and it can persist all the changes made to the Corpus instances it has created.