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.
Related
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.
I am implementing some classes in my application and I am little bit confused on choosing AppContext vs AppConfiguration.
My application configs are in YAML files which are parsed in application startup. Currently we are planning AppContext for just simple properties and AppConfiguration for getting complex properties/arrays.
ApplicationContext is basically backbone of running Spring, while configuration is definition how to do that. So context must know how to instantiate a bean - that is why bean factory is mandatory. Also context can have parent context. There are some other things that context is responsible for - please read the doc.
Configuration can define context, or provide other static information used by the app to do what is needed. That information can be taken from many sources, can be refreshed, and so on - but still - that is more like parameter, input for context.
I am a beginner of Spring and I still can't understand clearly what Bean is. From its definition, it seems a object that is determined by some pre-set configuration files or using annotation on a class. Once the spring starts up, the bean has been created. But can Spring use DI to create some instances of which attributes are not pre-determined?(Like, a user posts a json from website to Spring. And this json contains some data that are used to new a instance. Can Spring use this json to create the instance by using DI?)
Bean is just the object created by your spring application. As you know any spring application has several interacting objects working together to give rise to the desired programmed behavior.
A Bean is basically a managed object i.e at run time the IOC container creates the bean object based on its definition supplied by the coder or as configured in the apllicationContext.xml file under beans tag, and injects it to other classes as required.
Any Spring application is basically a conglomeration of various objects interacting with each other, these objects or beans collaborate to create the application.
A Bean's lifecycle is managed by the Spring IOC container.
The JSON consumed by the Spring Application is taken care of by the HttpMessageConverter. When recieving a new request, the Spring framework will use the content-type header to determine the media type of the request.
It will then try to find the corresponding converter, available in the classpath of the application, to convert the Request body.
Thus its clear that the incoming request body object is not managed by the Spring IOC container and hence is not a Bean.
But these deserialized instances are used as Data Transfer Objects in a Spring application's various layers like, service, DAO, controller.
Spring beans are the objects that comprise your application and are managed by the Spring framework. Comparing them to the concepts of JavaBeans and POJOs provides some explanatory context, and the Spring reference documentation contains extensive documentation of Spring beans, including this summary:
A bean definition essentially is a recipe for creating one or more
objects. The container looks at the recipe for a named bean when
asked, and uses the configuration metadata encapsulated by that bean
definition to create (or acquire) an actual object.
Also included in the reference documentation are descriptions of various ways to instantiate beans via an xml-based or annotation-based configuration approach as well as the Java Config approach (which also uses annotations). This is managed by the Spring BeanFactory interface (API here; source here).
The #Bean annotation is used to indicate that a method instantiates,
configures and initializes a new object to be managed by the Spring
IoC container. For those familiar with Spring’s XML
configuration the #Bean annotation plays the same role as the
element. You can use #Bean annotated methods with any Spring
#Component, however, they are most often used with #Configuration
beans.
You refer in the question to Dependency Injection (DI), a design pattern based on the Inversion of Control principle, which is a critical part of the Spring Framework, particularly for bean instantiation. DI allows values to be passed into the object from outside. The Spring documentation describes both the constructor-based and setter-based approaches to DI provided by the Spring IoC container for instantiating objects (beans).
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.
I am studying for the Spring Core certification and I have following doubt about this question:
What is meant by “container” and how do you create one?
I know that the Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application. These objects are called Spring Beans which we will discuss in next chapter.
And I know that there exist 2 containers:
Spring BeanFactory Container: This is the simplest container providing basic support for DI and defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purposes of backward compatibility with the large number of third-party frameworks that integrate with Spring.
Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.
Ok...this is pretty clear for me but what is the correct answer about How to create a container?
I think that it is automatically created by the Spring when it reads the configuration class or the XML configuration file.
Or not? What am I missing?
In short, "The Container" is a Spring instance in charge of managing the lifecycle of your beans.
To create one, basically, you should do something like
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
Remember replacing /application-context.xml by the file where you define your own Spring beans.
Take a look at http://www.springbyexample.org/examples/intro-to-ioc-creating-a-spring-application.html
You could also substitute the xml by a configuration class. On that case you should have something like this:
#Configuration
public class Myconfig{
#Bean
public MyBean myBean(){
return new MyBean();
}
}
For this, take a look at http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm