1

In a Spring MVC app, will a new instance of Singleton Class in WebApplicationContext ,be created if the application is closed and then started again?

Say there is a singleton scoped DAO class with some member variables(states) that were modified in the application and then the application was closed. Now when we run that app again, would the previous changes(made before the application was closed) be still there for that DAO or it will be a fresh singleton instance when the app restarts ?

2 Answers2

1

Fresh singleton instance.

Assuming that by "Singleton" you mean bean scope:

  • Singleton scoped bean is created by IoC container during startup of application, and then it is stored there. So, anytime you inject a class of specific type, IoC container returns that single instance it created

  • IoC container in Spring applications can configure bean only according to configuration metadata (check annotation-based and java-based configuration). IoC container is represented by ApplicationContext class.

ApplicationContext "lives" only when application lives. When application is stopped, ApplicationContext dies, and loses all beans with all their variables values.

DAO pattern concerns creating interface for communication with data source (in persistence layer, by using e.g. EntityManager, configured properly with metadata stored in e.g. application.properties). If you have a domain object (object, which "represents" database record), that have been modified inside application and not saved somewhere externally (e.g. in database), than it is lost, when application stops.

R-tooR
  • 106
  • 4
1

If it was a web application, then application will be down when the server stops or undeploys the given war if war was the artifact, or in case of jar(embedded server like in spring boot) application closes by terminating the program by quitting. In this case when application is quitted, jvm process will also quit and the spring container inside your application will also quit with it, and when spring container is no longer up, the objects contained in it will also be not available.

Hence, you will get a fresh instance on app restart.

Yogesh Sharma
  • 280
  • 1
  • 13