【问题标题】:Setting Spring bean property value in ApplicationContext without using properties file在 ApplicationContext 中设置 Spring bean 属性值而不使用属性文件
【发布时间】:2013-05-09 14:08:51
【问题描述】:

我想在我的应用程序上下文中更改我的 bean 属性的值,而不从属性文件中读取。我将获取属性对象中设置的属性值。在调用 api 接口时,properties 对象将传递给我的 api。

【问题讨论】:

    标签: spring applicationcontext


    【解决方案1】:

    您可以通过自定义 ApplicationContextInitializer 和使用 PropertySource 来实现 叫PropertiesPropertySource

    以这种方式创建自定义 ApplicationContextInitializer:

    public class PropertyRegisterAppInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>{
    
        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            MutablePropertySources sources = applicationContext.getEnvironment().getPropertySources();
            Properties props = new Properties();
            props.put("testkey", "testval");
            sources.addFirst(new PropertiesPropertySource("propertiesSource", props ));
        }
    
    }
    

    注册这个ApplicationContextInitializerweb.xml文件:

    <context-param>
        <param-name>contextInitializerClasses</param-name>
        <param-value>props.PropertyRegisterAppInitializer</param-value>
    </context-param>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 2011-06-03
      • 1970-01-01
      相关资源
      最近更新 更多