Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a spring boot application with multiple child contexts

I'm trying to create an application using spring boot with an hierarchical application context. My current main method looks like:

public static void main(String[] args) {
    new SpringApplicationBuilder(TestApplication.class)
            .child(AuditServiceConfiguration.class).web(true)
            .child(TaskServiceConfiguration.class).web(true)
            .run(args);
}

and the two children configurations are annotated with:

@EnableAutoConfiguration
@Configuration

The idea is to have a parent context containing all common beans and each child context to run its own MVC while being isolated from its siblings.

Unfortunately when I run the above, only the last child context is initialised and started.

Any pointers in the right direction would be greatly appreciated.

Regards,

Alessandro

like image 497
Alessandro Di Bella Avatar asked Aug 19 '15 13:08

Alessandro Di Bella


People also ask

Can we have multiple application context in Spring boot?

We can have multiple application contexts that share a parent-child relationship. A context hierarchy allows multiple child contexts to share beans which reside in the parent context. Each child context can override configuration inherited from the parent context.

Can Spring boot applications have two main methods?

After the creation of this class, we will have two new main classes with two public static void main(String args[]) methods. As we know from Java basics, we can only have one main method in a Java application.

What is SpringApplicationBuilder?

SpringApplicationBuilder is a builder for SpringApplication and ApplicationContext instances with convenient fluent API and context hierarchy support.


1 Answers

The child(...) method creates and returns another SpringApplicationBuilder, so when you call that second child(...) method, you are not instantiating a brother for the child, you are making a child on the first child, which makes the parent become a grandpa.

Jokes aside, have a look at the sibling(...) method which allows to create another context with the same parent.

You can also check out the source to see exactly what is going on.

like image 151
ESala Avatar answered Sep 30 '22 08:09

ESala