【问题标题】:Spring MVC: configure properties from before bean creationSpring MVC:在创建 bean 之前配置属性
【发布时间】:2022-08-20 02:39:16
【问题描述】:

我有一个场景,我想在创建/初始化任何 bean 之前以编程方式将属性注入 Spring:

  1. bean(不可修改)配置为ConditionalOnProperty,因此需要在创建之前设置属性。
  2. 属性需要以编程方式动态配置,而不是通过属性文件(我们调用 API 并使用结果来设置属性值)。

    我看到ApplicationContext 有办法获取当前环境的属性源(通过ConfigurableEnvironment),但我不确定如何在bean 初始化之前注入Spring 生命周期来配置ApplicationContext

    我知道BeanFactoryPostProcessor 是在bean 初始化之前发生的一个钩子,但是我看不到在其中获取ApplicationContext 实例的方法。

    如何实现?

    注意:应用程序本身是 Spring Web/MVC,而不是 Spring Boot。第三方库内部使用 Spring Boot 类 (ConditionalOnProperty)。

  • 如果它不是弹簧启动,那么您将如何处理ConditionalOnProperty,因为它来自 Spring Boot 而不是普通的弹簧。 2 是什么意思,什么是属性文件不可配置的?您将它们放在文件系统上,修改它们并启动应用程序。他们不必是应用程序的一部分吗?
  • 好消息...我没有意识到 ConditionalOnProperty 是 Spring Boot。事实证明,我们正在使用的第三方库(来自我们的 MVC 应用程序)在内部使用 Spring Boot 类。
  • 至于 #2,我们调用 API 并使用结果来设置属性值。我在澄清的问题中更新了相同的内容。
  • 只需将其设为属性源或使用ApplicationContextInitializer 调用端点,准备MapPropertySource 并将其添加到Environment

标签: java spring spring-mvc applicationcontext


【解决方案1】:

根据@m-deinum 的评论,我能够让它与以下内容一起工作:

public class MyPropertyInitializer extends WebMvcConfigurerAdapter implements WebApplicationInitializer, ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        String initializerClasses = servletContext.getInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM);
        String initClassName = this.getClass().getName();
        if (StringUtils.isNotBlank(initializerClasses)) {
            initializerClasses += "," + initClassName;
        } else {
            initializerClasses = initClassName;
        }
        servletContext.setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, initializerClasses);
    }

    @Override
    public void initialize(ConfigurableApplicationContext context) {
        Properties props = getCustomProperties();
        PropertySource<?> propertySource = new PropertiesPropertySource("my-custom-props", props);
        context.getEnvironment().getPropertySources().addLast(propertySource);
    }

    protected Properties getCustomProperties() {
        Properties props = new Properties();
        // do logic to set desired values
        return props;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多