在ApplicationContext中设置SpringBean属性值而不使用属性文件

在ApplicationContext中设置SpringBean属性值而不使用属性文件,spring,applicationcontext,Spring,Applicationcontext,我想在应用程序上下文中更改bean属性的值,而不从属性文件中读取。我将在properties对象中设置属性值。属性对象将在调用api接口时传递给我的api。您可以通过自定义并使用PropertySource 叫 通过以下方式创建自定义ApplicationContextInitializer: public class PropertyRegisterAppInitializer implements ApplicationContextInitializer<ConfigurableAp

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

您可以通过自定义并使用
PropertySource

通过以下方式创建自定义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 ));
    }

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