Spring based web application: Existing: The context is loaded from file("web.xml") and properties required for application are being loaded from properties file referred in xml context file.
New: Now properties should be read from zookeeper (along with properties file). Required java code for reading the properties is done by using ZookeeperPropertySource
Problem: Where do i need to insert the java code so that the properties will be loaded from zookeeper along with the initialization of application context?
I am unable to achieve this using ApplicationEventListener (as ContextStartedEvent is not triggered automatically) and BeanFactoryPostProcessor (Environment is not available to bind the properties)
Solution:
Create a new class extending "ContextLoaderListener" class and override the method "WebApplicationContext createWebApplicationContext(ServletContext sc)". As WebApplicationContext will be available here, ZookeeperPropertySource can be set to the environment.
Sample Code:
@Override protected WebApplicationContext createWebApplicationContext(ServletContext servletContext) { WebApplicationContext webApplicationContext = super.createWebApplicationContext(servletContext); loadZookeeperPropertySource(webApplicationContext.getEnvironment()); return webApplicationContext; }
loadZookeeperPropertySource(Environment environment) is a method where properties sources are loaded from zookeeper using ZookeeperPropertySourceLocator and set to the environment