Essential difference between Servlet context and Spring application context - java

I'm reading the spring framework documentation and now I'm at application scope concept. What the documentation says about that concept is this:
This is somewhat similar to a Spring singleton bean but differs in two
important ways: It is a singleton per ServletContext, not per Spring
ApplicationContext
To me, what's unclear is how can we imagine the relationship between Spring application context and Servlet context.
I'd assume that there two possible cases for the relationship between them:
I
II
So, how does the Spring application context relate with Servlet context? Is it case I or case II or neither of them?

It's neither of them.
ServletContext is the standard Java EE application scope. Each deployed webapp has one and only one servlet context.
Inside this webapp, you can have one (typically) or several Spring application contexts: one per Spring-MVC dispatcher servlet.

Related

What is the default scope for a spring controller component?

I'm diving into the spring bean scopes and application contexts topics and try to understand some concepts.
I understood that there is three main contexts. ApplicationContext (which is the context for a standalone app), WebApplicationContext for web based app (that extends ApplicationContext) and ServletContext (that is not Spring Related but a JEE thing, also related to web applications).
a WebApplicationContext contains all the Web related beans (controllers, ViewResolver etc ....), extends an ApplicationContext and reference a ServletContext
an ApplicationContext contains beans with singleton and prototype scope and
a WebApplicationContext adds three scopes : request, session, websocket and application but application scoped beans are related to the ServletContext referenced in the WebApplicationContext.
What I'm not sure to understand is :
if controller components are contained in the WebApplicationContext, what is their default scope ? I thought it was singleton but in this case it makes no sense because the WebApplicationContext that contains those beans dies when the server is shut down
the documentation says that application scope is "somewhat similar to a Spring singleton bean but differs in two important ways: It is a singleton per ServletContext, not per Spring ApplicationContext (for which there may be several in any given web application), and it is actually exposed and therefore visible as a ServletContext attribute." Its clear, but I do not understand how we can have multiple servletContext for one applicationContext, I didn't find any use case for that. I've seen a usecase for multiple WebApplicationContext in the same app, like an app whith a REST API and a web front, but in this case, there is only one applicationContext and (I thought) only one servletContext shared by multiple WebApplicationContext.
I don't think there is a conflict between that Controller scope being a Singleton and the WebApplicationContext that contains those beans dies when the server is shut down,
for the controller scope being a Singleton this means that the FactoryBeans creates one and only one istance of this controller and use it whenever it's called.

Use of Bean configuration XML File

I am a new user of Spring framework. I am facing some confusion in understanding the difference between core spring framework and spring boot. As far as I understand, Spring boot is a framework which performs the initial setup automatically (like Setting up Maven dependencies and downloading the jar files) and comes with an embedded Tomcat server which makes it ready to deploy in just one click., Whereas, Spring MVC requires manual setup. All the tutorials that I watched for core spring show bean configuration using bean factory which configures the beans using a .XML file. In Spring boot, this bean configuration file is absent. My question is, what is the use of this bean configuration file? I did not find any legitimate use of this file in making a REST service with spring. I didn't see any use of the Application Context, Bean Factory in creating web application. Can someone point out how can bean factory be used in Spring web apps? Is there any fundamental difference between core spring and spring boot other than the additional components?
The Spring application context is essentially the "pool" of beans (service objects, which include controllers, converters, data-access objects, and so on) and related information that define an application; I recommend the reference introduction. In theory, you can get complicated with the context setup and have hierarchical organization and such, but in most real-world cases you just have a single plain context.
Inside this context you need to install all of the beans that provide the logic for your application. There are several possible ways to do this, but the two main ways are by providing XML files with have directives like bean (define an individual bean) or component-scan (automatically search for classes with certain annotations, including #Controller) and by using Java classes annotated with #Configuration, which can use annotations and #Bean methods.
The XML style is generally older, and newer applications mostly use Java configuration, but both provide entries that are collected into the context, and you can use both simultaneously. However, in any application, you have to provide some way of getting the registration started, and you will typically have one "root" XML file or configuration class that then imports other XML files and/or configuration classes. In a legacy web.xml-based application, you specify this in your servlet configuration file.
Spring Boot is, as you said, essentially a collection of ready-to-go configuration classes along with a mechanism for automatically detecting configurations and activating them. Even this requires a configuration root, though! This is the #EnableAutoConfiguration instruction, frequently used through its composite #SpringBootApplication. The application context and configuration mechanisms work normally once Boot finds them and pulls them in. Spring knows where to get started because you give it an explicit instruction to build a context starting with that entry point, usually with SpringApplication.run(MyApplication.class, args).
The embedded-server configuration just happens to be a particular set of configuration that is really useful and comes with one of the Boot starter packages. There's nothing there that you couldn't do in a non-Boot application.

Why does fields in injected class become null - JavaFX with Spring [duplicate]

The definition of the spring ApplicationContext is very ambiguous, I almost finish a whole book of tutorial but still cannot understand what is the ApplicationContext stand for.
According the Spring API, ApplicationContext is:
Central interface to provide configuration for an application. This is read-only while the application is running, but may be reloaded if
the implementation supports this.
The root interface for accessing a Spring bean container. This is the basic client view of a bean container.
From above, my questions are:
1) I keep seeing the book mentioned "container", what is the container refer to? One container does it mean one java process? or one container refer to one ApplicationContext object?
2) If i instantiate two ApplicationContext in one java application (both in main body), are these two interfaces to one central container? Or two separate instances? See the code below, what is the difference between context1 and context2? If there is a Singleton in Beans.xml, it is invoked by context1 and context2, are they two separated instances or the same instance?
ApplicationContext context1 = new ClassPathXmlApplicationContext("Beans.xml");
ApplicationContext context2 = new ClassPathXmlApplicationContext("Beans.xml");
First you questions :
1) I keep seeing the book mentioned "container", what is the container refer to? One container does it mean one java process? or one container refer to one ApplicationContext object?
The ApplicationContext is the central interface, but the underlying container is a BeanFactory. More exactly, BeanFactory is a lower level interface implemented by all Application contextes from which you get the Beans. In that sense, I think that the word container stands here for the BeanFactory - one per ApplicationContext.
2) If i instantiate two ApplicationContext in one java application (one Main body), are these two interface to one central container? Or two separate different instance? See the code below, what is the difference between context1 and context2? If there is a Singleton in Beans.xml, it is invoked by context1 and context2, are they two separated instance or same instance?
ApplicationContext context1 = new ClassPathXmlApplicationContext("Beans.xml");
ApplicationContext context2 = new ClassPathXmlApplicationContext("Beans.xml");>
With that instanciations, you will get 2 totally independent application contexts. One bean declared in first will not be found in the other.
BUT
It is common to have more than one application context in a Web application, because Spring has a notion of hierachies of ApplicationContext. You could declare them as :
ApplicationContext context1 = new ClassPathXmlApplicationContext("Beans.xml");
ApplicationContext context2 = new ClassPathXmlApplicationContext("Beans.xml", context1);>
Here you can retrieve from context1 only beans declared in it, but from context2 you will retrieve beans from context2 and context1. Specifically, beans are first looked for in context2 and if not found then looked for in context1.
This is used in Spring MVC where you normally have one root context (for all beans not directly related to the MVC DispatcherServlet) and one child context dedicated to the DispatcherServlet that will contain the beans for controllers, views, interceptors, etc.
By container they refer to the core spring Inversion of Control container. The container provides a way to initialize/bootstrap your application (loading the configuration in xml files or annotations), through use of reflection, and to manage the lifecycle of Java objects, which are called beans or managed objects.
During this initial phase, you do not have (normally, yet it is possible) control in your application, instead you will get a completely initialized state for the application when the bootstrapping is done (or nothing, in case it fails).
It is a replacement, or possibly an addition, to what is called an EJB3 container; yet, the spring provided one fails to adhere to the EJB defined standard. Historically, adoption of EJB has been limited by the complexity of that specification, with spring being a newly created project for having EJB3 comparable features running on a J2SE jvm and without an EJB container, and with much easier configuration.
ApplicationContext (as an interface, and by the direct implementation flavours) is the mean of implementing this IoC container, as opposed to the BeanFactory, which is now (a sparsely used and) more direct way of managing beans, which by the way provides the base implementation features for the ApplicationContext.
As per your second question, you can have multiple instances of ApplicationContexts, in that case, they will be completely isolated, each with its own configuration.
I keep seeing the book mentioned "container", what is the container
refer to? One container does it mean one java process? or one
container refer to one ApplicationContext object?
Here container means spring container which is nothing but ApplicationContext. This internally reads spring configuration and loads the classes based on configuration. You may think it as SpringProcessor which provides the various functionality like bean initialization, injection, i18n, bean Post processing etc off the shelf
with
ApplicationContext context1 = new
ClassPathXmlApplicationContext("Beans.xml"); ApplicationContext
context2 = new ClassPathXmlApplicationContext("Beans.xml");
There will be two conatiners , hence two singleton beans. Here singleton means singleton instance per container. Ideally you should have only one container until and unless you have a reason for two. For learning purpose it makes sense to understand the concepts
ApplicationContext is an implementation of a Spring container. In simple words Spring container manages the entire Spring application via an ApplicationContext. Spring container via ApplicationContext manages the life cycle of a Spring bean i;e from initiation to destruction.
A spring container is nested inside a J2EE container.
I keep seeing the book mentioned "container", what is the container
refer to? One container does it mean one java process? or one
container refer to one ApplicationContext object?
A container manages the life cycle of an object. Tomcat is a an example of a container. Just like Spring container manages the app via ApplicationContext a J2EE container Tomcat manages the app via web.xml
A container provides communications support. Security in a web application. JSP support, Internationalization, event-propagation & many other features. It supports multithreading, spawns a new thread for every request for a resource. You don't have to explicitly write the code for that. Just like a spring container, a J2ee container manages a servlet life cycle.
If i instantiate two ApplicationContext in one java application (one
Main body), are these two interface to one central container?
If you want to instantiate multiple ApplicationContexts in your application. It will be in a parent child hierarchy. There will be one root ApplicationContext & then there will be child ApplicationContext respective to every DispatcherServlet. Beans global to the application will be defined in the root ApplicationContext. All the ApplicationContexts will be managed by only one spring container.
container is a Java object, an instance of one of ApplicationContext implementations like ClassPathXmlApplicationContext.
It is 2 different containers, if Beans.xml has a singleton bean B1, then context1.getBean("B1") and context2.getBean("B1") will return 2 different instances of B1
You added a "java-ee" tag. Spring is often used in web applications running on a application server. Typically each web application would have it's own application. The web applications are separated and probably that is what is called container in the documentation as you cannot regularly share variables with different applications / containers.
You can have two contexts within an application. If you have two contexts each will have its own singleton.
I keep seeing the book mentioned "container", what is the container refer to? One container does it mean one java process? or one container refers to one ApplicationContext object?
In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.
The interface org.springframework.context.ApplicationContext represents the Spring IoC container. The container gets details or instructions i.e. what objects need to be instantiated, configure and assembly by reading configuring metadata.
Application classes are combined with configuration metadata so that after the ApplicationContext is created and initialized, you have a fully configured and executable system or application.
If i instantiate two ApplicationContext in one java application (one Main body), are these two interface to one central container? Or two separate different instance? See the code below, what is the difference between context1 and context2? If there is a Singleton in Beans.xml, it is invoked by context1 and context2, are they two separated instance or same instance?
As mentioned by others as well you can have multiple application contexts.

What does it mean in Spring 3, web-aware application context

I am trying to setup a session scoped bean but the spring document said that session scope is only applicable on web-aware application context. No further explanation in the doc. Can someone clarify this?
This means that you can only use the session scoped beans in a an application deployed to a web server. Spring can be used in applications that run in standard JVMs along with applications that run in servlet containers (Tomcat, etc). Session, however, only exists in web servers so it has no meaning if the application is running in a standard desktop environment.
There are basically 5 types of scopes available for spring bean.
1)Singleton
2)Prototype
3)Request
4)Session
5)Global-Session
The first two scopes can be used with any type of spring applications.
But the remaining 3 are related to web applications. They can be used only with the spring applications which are involved in web.
Web aware means when the application provides web endpoints for third party client. I.E When the application contains at least one RestController . You can do this by simply adding #RestController annotation to your class.
ApplicationContext is an interface, spring ships multiple ApplicationContext implementations, according to documentation you need to use one that is web-aware.
The request, session, application, and websocket scopes are available only if you use a web-aware Spring ApplicationContext implementation (such as XmlWebApplicationContext). If you use these scopes with regular Spring IoC containers, such as the ClassPathXmlApplicationContext, an IllegalStateException that complains about an unknown bean scope is thrown.
And as of spring framework core (6.0.4) further configuration might be required:
To support the scoping of beans at the request, session, application, and websocket levels (web-scoped beans), some minor initial configuration is required before you define your beans.
...
If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by the Spring DispatcherServlet, no special setup is necessary. DispatcherServlet already exposes all relevant state.
If you use a Servlet web container, with requests processed outside of Spring’s DispatcherServlet (for example, when using JSF), you need to register the org.springframework.web.context.request.RequestContextListener ServletRequestListener. This can be done programmatically by using the WebApplicationInitializer interface. Alternatively, add the following declaration to your web application’s web.xml file:
<web-app>
...
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>
Spring boot will automatically configure this for you (couldn't find documentation mentioning this explicitly).

dispatcher-servlet.xml and application-context.xml

Why do we use dispatcher
servlet.xml?
Is it something like web.xml?
Is application and dispatcher xmls
different from each other, are there
any similar things which both can
do?
I have a value, now i need to send
it to another class? can i do it via
application-context.xml
In addition to Nathans' answer - the dispatcher-servlet.xml defines a child context of the base application context (define in applicationContext.xml)
Child contexts have access to all the beans defined in the parent context, but parents don't have access to beans in the child contexts.
Because people don't want one humongous application-context.xml, they split them up by application layer.
No, it's just a Spring application context file.
They do the same thing.
That's not what it's for, it's for defining what your spring-managed objects get injected with.
Dispatcher servlet.xml is just the convention followed by the Spring front controller for web MVC applications. If you don't use Spring web MVC, you need not have a dispatcher-servlet.xml
web.xml is the configuration file required by a Java web app. You must have a web.xml for a Java web app, but the Spring servlet.xml is only required if you use Spring web MVC.
The Spring servlet XML is just part of a Spring web application configuration. You can put all your Spring configuration in the single XML file if you wish, but usually people have more than one.
Spring's bean factory creates objects and injects their dependencies. Your code does the rest. Define what "send it to another class" means to you.

Categories