Bean visibility in context hierarchy¶
Bean visibility in context hierarchy refers to the access rules governing [[Spring]] Beans across multiple ApplicationContext instances organized in a parent-child relationship^[600-developer__java__spring__multipleApplicationContext.md].
Hierarchy Structure¶
In Spring, multiple application contexts can be organized into a hierarchy. A specific context is designated as the parent to another child context^[600-developer__java__spring__multipleApplicationContext.md]. This relationship is established programmatically using the setParent(ApplicationContext parent) method^[600-developer__java__spring__multipleApplicationContext.md].
When a parent is set, the child's environment merges with the parent's environment if the parent is non-null and its environment is an instance of ConfigurableEnvironment^[600-developer__java__spring__multipleApplicationContext.md].
Visibility Rules¶
The hierarchy enforces a strict, unidirectional visibility model:
- Child sees Parent: Beans defined in a parent context are visible and accessible to the child context^[600-developer__java__spring__multipleApplicationContext.md]. This allows a child context to access and utilize beans registered in its ancestors (including the root context).
- Parent does not see Child: Beans defined in a child context are not visible to the parent context^[600-developer__java__spring__multipleApplicationContext.md]. A parent context cannot retrieve beans that are defined exclusively within its children.
This behavior is often summarized as "子容器可以看到根容器中定义的beans,反之不行" (Child containers can see beans defined in the root container, but not vice versa)^[600-developer__java__spring__multipleApplicationContext.md].
Implications¶
This design allows for effective separation of concerns. A root or parent context often contains shared infrastructure beans (e.g., data sources, services), while child contexts contain specific beans (e.g., controllers specific to a module) that depend on the shared infrastructure. The child can access the infrastructure, but the infrastructure remains isolated from the specific implementation details of the child.
Sources¶
600-developer__java__spring__multipleApplicationContext.md