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.
Annotated spring beans in my spring-cloud application are being created twice. I assume this is because they get constructed into the bootstrap context and then into a child application context.
For me this is undesirable because some are annotated with #Scheduled to perform periodic refreshes of the data that they provide from a backend data source and this is happening twice in quick succession once for each context.
If it's not otherwise harmful then can I disable all of the application beans from being created in the bootstrap context? If not then can I detect in code when I'm running in the bootstrap context? I use entirely annotation-based beans with component scanning enabled on the Camden SR4 release.
OK I solved this myself. It was down to two different issues in the code and nothing to do with multiple contexts.
Firstly my long held assumption that an #PostConstruct method is only ever called once was false. Moving my one-off bean initialisation code to an implementation of ApplicationListener<ApplicationReadyEvent> solved that one.
Secondly I got bit by multiple initialisation of a bean with an #Scheduled annotation causes the scheduler to run multiple times. To be fair, this behaviour is noted in the documentation. This was easily solved by moving the scheduled task creation to a regular java ScheduledExecutorService set up in the ApplicationReadyEvent implementation.
I have a singleton bean in my spring context (call it 'beanX' ) that, when started spins off a few other threads and creates some state on the file system.
So I want to stop it in a clean way so that resources are freed when the context is shut down.
I have annotated it with #Bean(destroyMethod = "shutdown") and that works as expected without any problems.
Further information is that this bean loads very early in the context startup sequence (as it has many other beans that use it directly and indirectly) and there are many other beans that loads after it.
Now to the problem: it is fairly common that when we do development one of the other beans fail to start and makes the startup of the spring context to fail - but in these cases the beanX is not shut down properly.
This is perhaps ok in 'productionCode' as that usually means that the whole jvm stops and then resources are cleaned up - BUT when we run our 1000+ unit test suite (and some of the tests has an error causing the context to crash) this becomes a real problem because the test JVM is not stopped between tests, and a new spring context is created after each failing test - even though the test that failed has not properly cleaned up after itself as beanX is started but never stopped!
Today my laptop created 5 million file handles and 13k threads when I ran the test suite because of this.
SO, the only way we could make this work currently is to make beanX be a public static field (ClassX.beanX) that is lazily initialized by the spring context - and then in our test code manually call the ClassX.beanX.shutdown() if any context loading error occurs.
But I am curios if there is a better/different 'Spring' way to do this?
You can use event handling in Spring.
Event handling in the ApplicationContext is provided through the
ApplicationEvent class and ApplicationListener interface. If a bean
that implements the ApplicationListener interface is deployed into the
context, every time an ApplicationEvent gets published to the
ApplicationContext, that bean is notified. Essentially, this is the
standard Observer design pattern.
Our Java Web application loads with over 1000 plugins that are all registered by us as Spring beans using the ApplicationContext#registerBeanDefinition() method. These beans often have other dependencies which we also register as spring beans using the same method (for a total of about 7,000 Spring bean definitions...not including our core application code).
The problem is that the startup time is long (approximately 6.5 minutes of just plugin bean definition loading). We would prefer to spread this load time out over a much longer period while our app is actually processing other requests utilizing plugins that have already had their bean definitions registered. Most of the plugins are seldom used. Thus, we would really like to lazily register our bean definitions (this is different from lazy-init of singleton beans which we already do today). However, this seems costly with any existing Spring ApplicationContext that supports 'hot' refresh() calls (as the Spring documentation refers to it).
The Spring ApplicationContext classes that support 'hot' refresh start by destroying all of the singleton beans. Most of our plugins are singletons, so each call to refresh() would cause most of our plugins to be destroyed and then recreated...costly. If we don't call refresh, then our newly loaded plugin beans will not be post-processed (e.g., AOP, etc...).
We can guarantee that when we are forced to load another plugin, we will also load any of its dependencies that are not already loaded. So, we would never ben in a situation where a loaded bean definition is invalid.
It seems to me that this calls for a new type of Spring ApplicationContext that supports 'hot' refresh, but only for the purpose of adding new bean definitions. Preexisting bean definitions are not removed/reloaded, and not re-processed by BeanFactoryPostProcessors on subsequent refresh() calls, and pre-existing singletons are not destroyed!
Does this already exist?. Is there a better solution that I'm overlooking?
This sounds like you're looking for #Lazy.
4.4.4 Lazy-initialized beans
A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.
I'm currently migrating a JBoss service class from AS5.1 to AS6 (not going to AS7 for a variety of reasons).
For AS5.1, the service implements a {serviceName}MBean and has a jboss-service.xml with attribute values. It's packaged in a jboss-sar, which is packaged in an EAR to be deployed. When deployed, the service fields are populated with the values from jboss-service.xml, and the service is automatically registered into JMX.
I would like to achieve the same thing using AS6, but would like the service to support CDI - so I'd like its new #Inject injection points to be satisfied. I need these to be satisfied in the object registered with JMX, so that methods called via JMX can reference injected fields, but I'm struggling to achieve this.
I've had to package the service in a jar, instead of a jboss-sar, for classloader reasons, but let's say it's otherwise unchanged. When deployed to AS6, all works as before - service goes into JMX, values from XML propagate to the object. However, the instance created does not have its CDI injection points satisfied, and neither does the object registered in JMX.
If I annotate the service class with #Startup and #javax.ejb.Singleton, but keep its interface and the jboss-service.xml, the object registered into JMX still does not have its CDI injection points satisfied. However if I programmattically deregister that bean, and re-register the instance in a #PostConstruct method, then the bean in JMX DOES have its injection points satisfied. However that bean no longer has the values specified in the jboss-service.xml.
So how can I get the best of both worlds? CDI and the usual JBoss service behaviour? What is the correct way to implement a JBoss service with CDI? I've been unable to find documentation on this. Hope someone can help.
Thanks,
Ben
As a worst-case fallback, you should be able to use the CDI extension API to get your service to be injected. I don't think you would need to write a fully-fledged extension, but if you have an initialisation hook in the service object, you can do this (lifted with minor editing from the docs, not compiled or tested):
public static <T> void inject(T object) {
BeanManager beanManager = (BeanManager)new InitialContext().lookup("java:comp/BeanManager");
AnnotatedType<T> type = beanManager.createAnnotatedType(object.getClass());
InjectionTarget<T> it = beanManager.createInjectionTarget(type);
CreationalContext ctx = beanManager.createCreationalContext(null);
it.inject(object, ctx);
it.postConstruct(object);
}
Basically, any object to that method will get injected. All the usual CDI annotations should work. Hopefully.
As mentioned in the comments above, it seems Tom's right - there's no 'nice' way of created a CDIed, JMX bean in one go, you either have to put your JMX bean in CDI, as is suggested above, or put you CDIed bean into JMX. We tried the former, but it appears the BeanManager isn't bound to JNDI at the point the service starts up.
So instead we went with CDI bean -> JMX. We're creating the services as Singleton EJBs, so their injection points are satisfied, and they then get registered/unregistered to JMX in their PostConstruct/PreDestroy methods, using German Escobar's excellent CDI portable extension (germanescobar.net/2010/01/cdi-portable-extension-jmx.html, community.jboss.org/thread/148750 is also helpful).
May try to use ApplicationScoped beans and get them to start by observing a ContainerInitialized(?) event, however, as we don't need all the features of an EJB. Haven't tried that yet, mind...