Will a new instance of Singleton scoped object in a WebApplicationContext be created if the application is closed and started again in Spring MVC - spring

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 ?

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.

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.

Related

ApplicationContext in Spring Boot [duplicate]

This question already has answers here:
application context. What is this?
(4 answers)
What is Application context and bean factory in spring framework [duplicate]
(1 answer)
Closed 3 years ago.
I have a Spring Boot app and it's running with Spring Data, MySQL, Spring Security and MVC. The app is running for me just as fine.
However, I keep hearing about ApplicationContext a lot and I was wondering when do I need to use it and would like to know what it does. Can someone give me an example and an overview of ApplicationContext and its use?
ApplicationContext is a core interface that Spring framework built on. If you're building a Spring application, you're already using the ApplicationContext. You can have great insight about this from Spring Framework Reference Documentation. As per this document, Spring framework consists with these modules;
The Context (spring-context) module builds on the solid base provided
by the Core and Beans modules: it is a means to access objects in a
framework-style manner that is similar to a JNDI registry. The Context
module inherits its features from the Beans module and adds support
for internationalization (using, for example, resource bundles), event
propagation, resource loading, and the transparent creation of
contexts by, for example, a Servlet container. The Context module also
supports Java EE features such as EJB, JMX, and basic remoting. The
ApplicationContext interface is the focal point of the Context module.
spring-context-support provides support for integrating common
third-party libraries into a Spring application context, in particular
for caching (EhCache, JCache) and scheduling (CommonJ, Quartz).
Spring ApplicationContext also inherits BeanFactory super-interface. So technically ApplicationContext is capable of doing all the things, BeanFactory interface is capable and much more. BeanFactory interface along with ApplicationContext provide the backbone of the Spring IoC container (Core container). Which is Bean management for your application.
The interface org.springframework.context.ApplicationContext
represents the Spring IoC container and is responsible for
instantiating, configuring, and assembling the aforementioned beans.
The container gets its instructions on what objects to instantiate,
configure, and assemble by reading configuration metadata. The
configuration metadata is represented in XML, Java annotations, or
Java code. It allows you to express the objects that compose your
application and the rich interdependencies between such objects.
ApplicationContext uses eager loading mechanism. So, every bean declared in your application, initialize right away after the application started and after, this ApplicationContext scope is pretty much read-only.
Initiate a Spring IoC container with custom bean definitions is pretty much staright forward.
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"daos.xml"});
Following file shows this daos.xml file content;
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountDao"
class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for data access objects go here -->
</beans>
After that you can access the beans define in the .xml like this;
JpaItemDao obj = (JpaItemDao) factory.getBean("itemDao");
These instances are now being initialized and managed by the ApplicationContext. But most users prefer to use #Bean annotation define beans to do the binding and #Autowired annotation to do the dependency injection. So, no need to manually feed a bean .xml to custom initialized ApplicationContext.
#Configuration
class SampleConfig {
#Bean
public JpaItemDao getJpaItemDao() {
return new JpaItemDao();
}
}
and inject in;
#Component
class SampleComponent {
#Autowired
private JpaItemDao itemDao;
public void doSomething() {
itemDao.save(); // Just an example.
}
}
Besided the bean management, ApplicationContext does some other important thing in the Spring core container. As per ApplicationContect javadoc, they are;
Bean factory methods for accessing application components. Inherited from ListableBeanFactory.
The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
The ability to publish events to registered listeners. Inherited from the ApplicationEventPublisher interface.
The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a
single parent context can be used by an entire web application, while
each servlet has its own child context that is independent of that of
any other servlet.
Also, checkout the sub-interfaces of ApplicationContext that specifically designed for work on different use cases like WebApplicationContext.
ApplicationContext is a core concept (arguably the most important one) of spring used also in spring boot of course but and ideally hidden from the programmers in both cases, meaning that the programmer should not directly interact with it in a business code of the application.
Technically its an interface that has many implementations, the relevant one is picked depending on in which environment you're running and how do you configure the application.
So does it do? Its a class that basically is a registry of all the beans that spring has loaded. In general, starting up the spring mean finding the beans to load and putting them in the application context (this is relevant for singletons only, prototype-scopes beans are not stored in the ApplicationContext).
Why does spring need it?
For many reasons, to name a few:
To manage lifecyle of the beans (when the application shuts down, all beans that have a destroy method should be called)
To execute a proper injection. When some class A depends on class B spring should inject class B into class A. So by the time of creating the class A, class B should already be created, right? So spring goes like this:
Creates B
Puts B into application context (registry)
Creates A
For injection goals: gets B from the application context and injects into A
// an illustration for the second bullet
class B {}
class A {
#Autowired
B b;
}
Now there are other things implemented technically in application context:
Events
Resource Loading
Inheritance of application contexts (advanced stuff, actually)
However now you have an overview of what it is.
Spring boot application encapsulates the application context but you can still access it from many places:
in the main method when the application starts it returns an application context]
you can inject it into configuration if you really need
its also possible to inject the application context into the business bean, although we shouldn't really do so.
In simple words:
Spring is popular for dependency Injection.
So all the bean definitions(Objects) will be created by the spring and maintained in the container. So all the bean life cycle will be taken care by spring container.
So ApplicationContext is a interface It has different implementations will be there to initialize the spring container.
So ApplicationContext is the reference to Spring Container.
Some popular implementations are:
AnnotationConfigWebApplicationContext,
ClassPathXmlApplicationContext,
FileSystemXmlApplicationContext,
XmlWebApplicationContext.
Reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html

How J2EE Application Server serves a single WebService Call

During a coding session for a project I ran into a doubt.
My doubt is, how title suggests, about how J2EE Application Server serves a single WebService Call​.
When a call to a WS is made by a client, the J2EE AS create a new thread to serve it? I don't need to worry about multiple and simultaneous calls to a WS implementation, right? (which is a Operation and a method in Java)
Another doubt is about #Autowired in Spring (with singleton instantiation which is the default).
In this web application, I'm creating a Spring Context in the usual way, in the web.xml I put the usual tag wich refers to a context-spring-xml config file using the ContextLoaderListener Spring class.
For instance:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-conf/spring-context.xml
</param-value>
</context-param>
In this case, for every bean which is #Autowired (with singleton) I've a single instance for the entire Application Server? Or every time a WS Call is made a thread is created and the single thread has its single instance of every defined bean in the spring xml config file?
Let's consider that the ServiceImplementation class is a spring bean itself, managed as singleton.
We use Apache Camel as ESB exposing service Consumer as SpringRouteBuilder classes.
When a call to a WS is made by a client, the J2EE AS create a new thread to serve it? I don't need to worry about multiple and simultaneous calls to a WS implementation, right?
Right. But you have to worry about your #Autowired singleton thread-safety.
It must not have any instance variables used during process of request/response. It may have only configuration/setting properties.
In this case, for every bean which is #Autowired (with singleton) I've a single instance for the entire Application Server?
Not right.
It will not be for the entire AS. It is in scope of your web application. That is about applications isolation from each other.
That means when same #Autowired class defined in two different web applications' Spring contexts (e.g spring-context.xml in web.xml inside both WAR) - each application Spring context will have its own singleton.

How to create initialized Spring bean (in session scope)

I am trying to create multi-tab (JavaScript tabs) interface for Spring/facelets application and I have s.c. window manager that holds array of windows (tabs). Each window (tab) contains Spring bean (session scope) which receive (as injections) other spring beans, e.g. for business services, DAO beans and so on. I am using Primefaces p:tabView for facelets part.
When user creates new tab, the new Spring bean (as part of the window/tab) should be created and added to the window manager bean (WindowManager.addWindow(...) has method that is colled from the p:commandButton and that creates window/tab and its session been). The question is - how to create this bean and initialize it (with injected beans)? One solution maybe is to call ctx.getBean("beanName"), but I am afraid to use this because it has name and this name seems to be unique.
Maybe programmatical creation of Spring beans is not good design (they should be created automatically but the web server/Spring context when they process the web requests), but it seems to be necessary in my case.
You must define that bean with scope "prototype", this setting causes that Spring context create a new fresh instance in every call to context.getBean("beanName");
To configure that, you can use:
#scope("prototype")
or
<bean id="beanName" class="com.foo.myBean" scope="prototype"/>
Depending on whether you are using java or xml configuration. Take a look to the Spring documentation for more details:
http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html

Can we undeploy a Spring container managed bean which is no more needed

I a get a get a bean from Spring container say
MyClass obj1 = Context.getBean("obj1");
After using obj1, I am sure that it will not be needed in rest of my application.
Then is there any way to ask Spring container to destroy the bean.
Atleast giving hint to Spring container that it is no more needed and spring my decide whether to destroy it or not (Similar to garbage collection)?
Make "obj1" a prototype-scoped bean. Then Spring will create a new instance of it each time you ask for it (make sure you are ok with this), and then it will not manage the instance any further, so when you are done with it and release all your references it can be garbage collected.
Prototype scope is like new, only giving you Spring-configured beans.
I don't think it will be possible for you to tell Spring container to destroy that bean. If you notice most of these beans created by Spring framework are Singleton that are supposed to give you same instance of the bean every time you get it injected into your code. A singleton by nature is supposed to live through the life of the application hence it cannot be destroyed.

#configurable Vaadin app controller not reinjecting after tomcat restart

I am using a #configurable annotated Vaadin controller together with my Spring context, and it is working fine - except when I need to restart Tomcat, and the sessions are deserialized. Then I get this for my Vaadin app:
org.springframework.beans.factory.wiring.BeanConfigurerSupport BeanFactory has not been set on BeanConfigurerSupport: Make sure this configurer runs in a Spring container. Unable to configure bean of type [web.vaadin.ui.BackOfficeApplication]. Proceeding without injection.
I am thinking that this can be because the vaadin app is reserializing before the spring bean factory has a chance to?
(I am using CTW - aspectj and Spring 3.1.1.RELEASE)
Note:
It seems in the log that these errors come before the "Root WebApplicationContext: initialization started". How can it be that the beans are being autowired before the context initialization is started?
I am not an expert on (de)serialization with Spring and Tomcat, and this is not an answer but might be a workaround.
If BackOfficeApplication is your Vaadin application then there is an alternative to using #Configurable on that class. Instead, create a per-Vaadin Application Spring application context XML file and add this to it to cause your BackOfficeApplication instances to be autowired, etc.:
<bean id="backOfficeApplication"
class="org.dellroad.stuff.vaadin.ContextApplication"
factory-method="get"/>
In general, #Configurable can be more troublesome than normal bean wiring because they require the configuration to occur at object construction rather than allowing the bean factory to do the wiring later on, where it may be better able to detect loops, enforce ordering, etc.
Ideally normal bean wiring should be used for singletons that are initialized once at the beginning of the application and #Configurable should be used for "on the fly" beans created randomly during normal operation.

Resources