Skip to content

setParent() Method

The setParent() method is a configuration function used within the Spring Framework to establish a hierarchical relationship between application contexts^[600-developer-java-spring-multipleapplicationcontext.md]. Specifically, it is available on the AnnotationConfigApplicationContext class to define a parent-child structure^[600-developer-java-spring-multipleapplicationcontext.md].

Functionality

This method allows a developer to designate an existing ApplicationContext as the parent of a newly created or initialized child context^[600-developer-java-spring-multipleapplicationcontext.md]. When a parent context is set, the environment configurations are merged into the child context^[600-developer-java-spring-multipleapplicationcontext.md].

Visibility and Bean Access

Implementing a parent-child hierarchy dictates the visibility of beans within the application^[600-developer-java-spring-multipleapplicationcontext.md].

  • Downward Visibility: Child contexts can access and retrieve beans defined in their parent (or root) contexts^[600-developer-java-spring-multipleapplicationcontext.md].
  • Upward Restriction: Parent contexts cannot access beans defined within their child contexts^[600-developer-java-spring-multipleapplicationcontext.md].

This creates a structure where multiple child contexts can share common beans defined in a root context while maintaining their own specific configurations^[600-developer-java-spring-multipleapplicationcontext.md].

Usage

When organizing multiple contexts, setParent() is typically called before the child context is refreshed^[600-developer-java-spring-multipleapplicationcontext.md].

[AnnotationConfigApplicationContext](<./annotationconfigapplicationcontext.md>) parentCtx = new [AnnotationConfigApplicationContext](<./annotationconfigapplicationcontext.md>)();
[AnnotationConfigApplicationContext](<./annotationconfigapplicationcontext.md>) childCtx = new [AnnotationConfigApplicationContext](<./annotationconfigapplicationcontext.md>)();

// ... Register beans ...

childCtx.setParent(parentCtx); // Establishes the hierarchy

parentCtx.refresh();
childCtx.refresh();

Sources

  • 600-developer-java-spring-multipleapplicationcontext.md