Spring 启动动态上下文创建(parent/child)

Spring Boot dynamic context creation (parent/child)

我正在使用 Spring Boot 与 Spring 集成,我想为每个 child() 上下文加载不同的属性。这可能吗?

此刻,我正在处理这个:(只有最相关的行)

SpringApplicationBuilder parent = new SpringApplicationBuilder(Main.class);
// Child sources (Will be inside a loop)
// Load the different environment ??
parent.child(ConfigDynamic.class); 
// End of child loading

parent.run(args);

我查看了 SpringApplicationBuilder child() 方法,属性从父级传播到 child:

child.properties(this.defaultProperties).environment(this.environment)
.additionalProfiles(this.additionalProfiles);

但我需要动态加载一些属性,如下例所示:

AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(Main.class);
parent.setId("parent");
Properties props = new Properties();
StandardEnvironment env = new StandardEnvironment();
AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
child.setId("child" + ++n);
child.setParent(parent);
child.register(ConfigDynamic.class);        
// populate properties for this adapter
props.setProperty("prop1", myProp1);
props.setProperty("prop2", myProp2);
env.getPropertySources().addLast(pps);
child.setEnvironment(env);
child.refresh();

从这个例子中提取:

这是因为某些 Spring 集成组件将从配置文件中动态加载。因此,我需要使用动态组件创建不同的上下文。

任何想法将不胜感激,谢谢

编辑 1:

我更新了示例:

SpringApplicationBuilder parent = new SpringApplicationBuilder(Main.class);

for start    
SpringApplicationBuilder child = parent.child(DynamicConfig.class);    

//Properties creation..
child.context().getEnvironment().getPropertySources().addLast(pps);
child.run(args);    
end for

parent.run(args);

但是现在,child() 上下文在 run() 方法之前为空并引发 NPE。

编辑 2:(工作中)

SpringApplicationBuilder parent = new SpringApplicationBuilder(Main.class);

for start    
SpringApplicationBuilder child = parent.child(DynamicConfig.class);    

PropertiesPropertySource pps = new PropertiesPropertySource("dynamicProps", props);  
StandardEnvironment env = new StandardEnvironment();
env.getPropertySources().addLast(pps);
child.environment(env);
child.run();    
end for

parent.run(args);

我绝对不明白的最后一件事是为什么我需要一个 parent 上下文,即使我所有的 @Component@Configuration 都是 Spring 集成组件并且可以加载为 child()。 parent context 是放置bus/or 组件以与不同children 通信的地方吗?我想这可能是一个内存问题,为每个上下文加载多个单例。

这应该有效...

SpringApplicationBuilder child = builder.child(ConfigDynamic.class);
...
child.context().getEnvironment().getPropertySources().addLast(pps);
...
child.run();