I'm going to create several Spring contexts with one parent context. Here is how I'm going to create parent context:
new ClassPathXmlApplicationContext(new String[] {"ApplicationContext/application.xml"})
And each parent context I want to create in following way:
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
configurer.setProperties(properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(appContext);
context.addBeanFactoryPostProcessor(configurer);
context.setConfigLocation("ApplicationContext/beans.xml");
context.refresh();
The idea is to have multiple child contexts with the same bean hierarchy in each of them (DAOs, services, data source, transaction manager, etc). The reason to have several contexts is in demand to have several different data sources (one per each application context actually). Database structure for each data source is the same. So, there are some questions.
PS. There is another way to handle multiple data sources described here. But this approach seems to be not really convenient in my case.
@ContextHierarchy is a class-level annotation that is used to define a hierarchy of ApplicationContexts for integration tests.
Simply put, the context path is a name with which a web application is accessed. It is the root of the application. By default, Spring Boot serves the content on the root context path (“/”). So, any Boot application with default configuration can be accessed as: http://localhost:8080/
Basic. The task of the DispatcherServlet is to send request to the specific Spring MVC controller. ContextLoaderListener reads the Spring configuration file (with value given against contextConfigLocation in web.xml ), parses it and loads the singleton bean defined in that config file.
What do you mean by safety? If you mean thread safety while bean initialization then yes, since the contexts are initialized one by one.
Beans are not visible across child contexts. The only beans visible in a context are its own and the ones in its parent contexts.
Yes. As per the answer to the last question.
I use this pattern quite extensively in my applications. There is common context which is shared by many other child contexts by making it their parent. It is quite useful when you want to run completely isolated contexts inside a single JVM, for example if you application is a mutli-tenant one. Then you can start/stop/restart application contexts tenant-wise without restarting the JVM.
This also allows a clear separation of data sources and transaction managers and allows one to shard their databases easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With