AnnotationConfigApplicationContext¶
AnnotationConfigApplicationContext is a concrete implementation of the ApplicationContext interface in the Spring Framework, designed specifically for registering and managing beans based on Java configuration annotations^[600-developer-java-spring-multipleapplicationcontext.md]. It serves as the core container for dependency injection in modern Spring applications, utilizing @Configuration classes and @Bean definitions to construct the object graph^[600-developer-java-spring-multipleapplicationcontext.md].
Instantiation¶
The context can be instantiated using a default constructor, after which configuration classes can be programmatically registered^[600-developer-java-spring-multipleapplicationcontext.md]. Alternatively, it may be constructed directly by passing configuration classes as arguments to the constructor^[600-developer-java-spring-multipleapplicationcontext.md].
// Programmatic registration
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.registerBean(Config01.class);
// Constructor-based registration
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config01.class);
Hierarchies¶
AnnotationConfigApplicationContext supports the creation of hierarchical container structures via the setParent(ApplicationContext parent) method^[600-developer-java-spring-multipleapplicationcontext.md]. This allows a "child" context to be linked to a "parent" (or root) context.
- Bean Visibility: A child context can access beans defined in itself and in its ancestor contexts^[600-developer-java-spring-multipleapplicationcontext.md].
- Isolation: Conversely, a parent context cannot access beans defined within its children^[600-developer-java-spring-multipleapplicationcontext.md].
- Environment Merging: When a parent is set, the
Environmentof the parent is merged into the child's environment if both instances areConfigurableEnvironment^[600-developer-java-spring-multipleapplicationcontext.md].
Lifecycle Management¶
The container requires an explicit refresh signal to complete its initialization and process registered beans^[600-developer-java-spring-multipleapplicationcontext.md].
Refresh Phase¶
The refresh() method triggers the processing of bean definitions and the wiring of dependencies^[600-developer-java-spring-multipleapplicationcontext.md]. In a hierarchy, the parent context must typically be refreshed before the children^[600-developer-java-spring-multipleapplicationcontext.md].
Shutdown Phase¶
The close() method is used to shutdown the context and release resources^[600-developer-java-spring-multipleapplicationcontext.md]. When a context is closed, its isActive() status returns false^[600-developer-java-spring-multipleapplicationcontext.md].
Sources¶
^[600-developer-java-spring-multipleapplicationcontext.md]