0

基于 Spring 的 Web 应用程序:现有:从文件(“web.xml”)加载上下文,应用程序所需的属性从 xml 上下文文件中引用的属性文件加载。

新:现在应该从 zookeeper 读取属性(连同属性文件)。使用 ZookeeperPropertySource 完成读取属性所需的 java 代码

问题:我需要在哪里插入java代码,以便从zookeeper加载属性以及应用程序上下文的初始化?

我无法使用 ApplicationEventListener (因为 ContextStartedEvent 不会自动触发)和 BeanFactoryPostProcessor (环境无法绑定属性)来实现这一点

4

1 回答 1

0

解决方案:
创建一个扩展“ContextLoaderListener”类的新类并覆盖方法“WebApplicationContext createWebApplicationContext(ServletContext sc)”。由于 WebApplicationContext 将在此处可用,因此可以将 ZookeeperPropertySource 设置为环境。

示例代码:

@覆盖
受保护的 WebApplicationContext createWebApplicationContext(ServletContext servletContext) {
    WebApplicationContext webApplicationContext = super.createWebApplicationContext(servletContext);
    loadZookeeperPropertySource(webApplicationContext.getEnvironment());
    返回 webApplicationContext;
}

loadZookeeperPropertySource(Environment environment) 是一种使用 ZookeeperPropertySourceLocator 从 Zookeeper 加载属性源并设置为环境的方法

于 2019-05-30T04:29:12.767 回答