2016-08-23 7 views
1

Я использую Spring Boot с интеграцией Spring, и я хотел бы загрузить различные свойства для каждого контекста child(). Это возможно?Создание динамического контекста Spring Boot (родительский/дочерний)

На данный момент я работаю с этим: (только наиболее значимые линии)

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.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 multiple imapAdapter

Причина в том, что некоторые компоненты интеграции Spring будут динамически загружаться из файла конфигурации. Таким образом, мне нужно создать различные контексты с динамическими компонентами.

Любая идея будет иметь в виду, спасибо

Edit 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.

Edit 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); 

Последнее, что я определенно не понимаю, почему мне нужен родительский контекст, даже если все мои @Component и @Configuration компоненты Spring Integration и может быть загружен как child(). Является ли родительский контекст местом, где можно поставить шину/компонент для общения с разными детьми? Я полагаю, что это может быть проблемой памяти, загружающей несколько синглтонов для каждого контекста.

ответ

0

Это должно работать ...

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

ребенка() вызывает исключения нулевого указателя. Я обновил вопрос. – crm86

 Смежные вопросы

  • Нет связанных вопросов^_^