I am using Spring Boot with Spring Integration and I would like to load different properties for each child()
context. Is this possible?
At this moment, I am working with this: (only the most relevant lines)
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);
I have reviewed the SpringApplicationBuilder child()
method and the properties are propagated from the father to the child:
child.properties(this.defaultProperties).environment(this.environment)
.additionalProfiles(this.additionalProfiles);
But I need to load some properties dynamically like the following example:
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();
Extracted from this example: Spring multiple imapAdapter
The reason to this is because some Spring Integration components will be loaded dynamically from a configuration file. Thus, I need to create different contexts with the dynamic components.
Any idea will be appreciated, thank you
Edit 1:
I updated the example:
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);
But now, the child()
context is null before run()
method and raises a NPE.
Edit 2: (Working)
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);
The last thing that I definitely do not understand is why I need a parent context even if all my @Component
and @Configuration
are Spring Integration components and could be loaded as child()
. Is the parent context the place to put bus/or component to communicate different children? I suposse that could be a memory problem loading several singletons for each context.