How to load properties into environment from zookeeper before initialising beans in web application

242 Views Asked by At

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)

1

There are 1 best solutions below

0
Anand Kumar On BEST ANSWER

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