"Original article, reprint please specify the source" "This address" http://www.cnblogs.com/zffenger/p/5813470.html
When using spring, we often need to get a ApplicationContext object and then get our configured Bean object from that object. ApplicationContext belongs to Org.springframework.context, is the manager of Springframework Bean, provides support for many functions of springframework.
is the UML Class View associated with ApplicationContext in the spring-4.3.2.release version (light green for the interface, light yellow for the Class):
Beanfactory Series Interface:
Public Interface Beanfactory
Beanfactory is the topmost interface of the Spring management bean, a bean container that manages a series of beans, each of which is uniquely determined using a string type name (or ID), which can be protot Ype or Singleton. Spring advocates the use of dependency injection (Dependency injection) to assemble beans. Beanfactory load the bean definition from "configuration source", the configuration source can be either an XML file or a properties file or even a database.
Public Interface extends Beanfactory
beanfactory Sub-interface hierarchicalbeanfactory is a hierarchical bean factory with property Parentbeanfactory. When the Bean object is fetched, if the corresponding bean does not exist in the current beanfactory, its direct parentbeanfactory is accessed to try to get the bean object. In addition, you can override the same bean with the parent beanfactory in the current beanfactory.
Public Interface extends Beanfactory
Listablebeanfactory inherits the Beanfactory, which implements the enumeration method to enumerate all the bean objects in the current beanfactory without having to obtain one by name. getbeandefinitionnames () If the Listablebeanfactory object is still a hierarchicalbeanfactory Method only returns the Bean object in the current beanfactory and does not go to the parent beanfactory query.
Other interfaces:
Public Interface Propertyresolver
The top-level interface of the profile parser, parsing the configuration file for property values, and so on
Public Interface extends Propertyresolver
Provides the required environment for the current application operation
Public Interface Environmentcapable
This is a environment Holder, there is only one method: Environment Getenvironment () is used to get the environment object
Public Interface Applicationeventpublisher
The function of this interface is the publish event, which sends a message to the event listener (Listener)
Public Interface Messagesource
The policy interface for parsing message, such as string GetMessage (String, object[], String, Locale), for supporting functions such as internationalization
Public Interface extends Resourceloader
Where Resourceloader is used to load resource files from a source (such as inputstream, etc.), Resourcepatternresolver is a subclass of Resourceloader, according to Path-pattern Load the resource.
ApplicationContext Interface:
Public Interface extends Environmentcapable, Listablebeanfactory, Hierarchicalbeanfactory, Messagesource, Applicationeventpublisher, Resourcepatternresolver
The point is that the ApplicationContext interface inherits numerous interfaces, integrates many interfaces, and provides basic functional support for spring operations. According to the "single responsibility Principle" of the program design, in fact each more top-level interface is "single duty", only provide a certain aspect of the function, and the ApplicationContext interface inherits a lot of interfaces, equivalent to have a lot of interface functions , Here's a look at its main features:
- First of all, it is a beanfactory, can manage, assemble the bean, can have the parent beanfactory implements the bean's level management (in this case, it can have the parent applicationcontext, Because ApplicationContext itself is a beanfactory. This is useful in Web projects, so that each servlet has its own context, and all servlets share a parent context, and it is listable to enumerate the managed bean objects.
- Second, it is a resourceloader that can load resource files;
- Thirdly, it can manage some of the functions of message internationalization.
- Also, it can publish events to the registered listener to implement the listening mechanism.
ApplicationContext Sub-interfaces:
The ApplicationContext interface has two direct sub-interfaces, namely:
Org.springframework.context.ConfigurableApplicationContext Org.springframework.web.context.WebApplicationContext
See these two sub-interfaces separately:
Public Interface extends ApplicationContext, Lifecycle, closeable
According to the interface name can be decided, the interface is configurable! The ApplicationContext interface itself is read-only, so sub-interface Configurableapplicationcontext provides such as SetID (), SetParent (), Setenvironment () and other methods to configure ApplicationContext.
Then look at the other two interfaces it inherits:
- The Lifecycle:lifecycle interface has a start (), Stop () and other methods for the management of the context life cycle;
- Closeable:closeable is an interface provided by the standard JDK for the final shutdown of component release resources;
Public Interface extends ApplicationContext
The interface provides Getservletcontext () only on the basis of the original interface and is used to provide contextual information to the servlet.
Public Interface extends Webapplicationcontext, Configurableapplicationcontext
Here Configurablewebapplicationcontext also combines the above two interfaces, providing a configurable, manageable, webapplicationcontext that can be closed, The interface also adds a set method such as Setservletcontext (), Setservletconfig () to assemble the webapplicationcontext.
Here ApplicationContext related interface is basically finished, summed up on the two main interfaces:
Org.springframework.context.ConfigurableApplicationContext Org.springframework.web.context.ConfigurableWebApplicationContext
For common applications, use the Configurableapplicationcontext interface implementation class as the Bean manager, for Web applications, using Configurablewebapplicationcontext The implementation class for the interface is the manager of the Bean. These two interfaces, structurally speaking, are inheritance relationships , which, by application, are peer relationships and provide strong support for spring in different fields.
ApplicationContext related implementation class design:
Spring is an excellent framework, with good structural design and interface abstraction, each of its interfaces is a highly abstract function specific to each module, the actual use of the interface is equivalent to the various implementation classes provided by the interface to provide complete service, It can be said that mastering the spring interface is equivalent to mastering most of spring's functionality.
There are many implementations of ApplicationContext, however
The various functions of the ApplicationContext interface are analyzed above, and the following will analyze how the implementation classes of the ApplicationContext implement the various functions of the above interface (PS. Confined to space, here only to indicate what the above functions in the implementation of the class in what way to achieve, as to its specific implementation process, each function can be taken out of a separate article, here is not detailed. As for the implementation class extending other interfaces or inheriting other parent classes, these are just implementations of the class in order to extend the functionality or to facilitate the implementation of the above interface to do things, the ApplicationContext interface abstraction out of the functionality has no effect or not much help, so omitted.
Taking Classpathxmlapplicationcontext as an example, its main inheritance relationship is as follows:
Org.springframework.context.support.AbstractApplicationContext Org.springframework.context.support.AbstractRefreshableApplicationContext Org.springframework.context.support.AbstractRefreshableConfigApplicationContext Org.springframework.context.support.AbstractXmlApplicationContext Org.springframework.context.support.ClassPathXmlApplicationContext
The top-level abstract class Abstractapplicationcontext implements the Configurableapplicationcontext interface.
extends Defaultresourceloader implements Configurableapplicationcontext, Disposablebean
According to the above, the parent class Defaultresourceloader and interface Disposablebean are omitted, focusing only on the interface Configurableapplicationcontext, recalling the main functions:
configable, (the interface itself extends the functionality) Lifecycle, // life cycle manageable Closeable,// Environmentcapable,// configurable environment Messagesource, // applicationeventpublisher, // Resourcepatternresolver,// load the resource specified by pattern listablebeanfactory, Hierarchicalbeanfactory,// manage the life cycle of the bean, which is the most important, and finally say
Then go back to the topmost abstract class Abstractapplicationcontext, which can be said to be the most code-Classpathxmlapplicationcontext class in the inheritance structure, and most of the above functions are also implemented in the class. This class adopts the template method pattern , realizes most of the logic of the above functions, and then extracts many protected methods (or abstract methods) for the subclass Override.
The implementation of each function is listed as follows:
configable: such as setparent/setenvironment and other methods, implemented by Abstractapplicationcontext. code example:
@Override public void SetParent (applicationcontext parent) { this . Parent = parent; if (parent! = null = Parent.getenvironment (); if (parentenvironment instanceof Configurableenvironment) {getenvironment (). Merge ((Configurableenviro nment) parentenvironment); } } }
Lifecycle: Abstractapplicationcontext has a lifecycleprocessor instance that manages its own life cycle, Abstractapplicationcontext lifecycle methods such as Start, Stop, etc. will be proxied to lifecycleprocessor for processing, code example:
@Override Public void start () { getlifecycleprocessor (). Start (); Publishevent (new contextstartedevent (this)); }
closeable: implemented by Abstractapplicationcontext, used to close applicationcontext destroy all beans, and if there is a JVM shutdown hook registered, It is also removed. code example:
@Override Public voidClose () {synchronized( This. Startupshutdownmonitor) {Doclose (); if( This. shutdownhook! =NULL) { Try{runtime.getruntime (). Removeshutdownhook ( This. Shutdownhook); }Catch(IllegalStateException ex) {//IGNORE-VM is already shutting down } } } }
environmentcapable: implemented by Abstractapplicationcontext, which holds a configurableenvironment instance, The Getenvironment method used to implement the Environmentcapable interface. code example:
@Override Public configurableenvironment getenvironment () { if (thisnull) { this. Environment = createenvironment (); } return This . Environment; }
Messagesource: Abstractapplicationcontext holds a Messagesource instance, and proxies the method of the Messagesource interface to the instance to complete. code example:
@Override Public string GetMessage (String code, Object args[], string defaultmessage, locale locale) { return g Etmessagesource (). GetMessage (code, args, defaultmessage, locale); }
Applicationeventpublisher: implemented by Abstractapplicationcontext, if there is a parent applicationcontext, The event is also published to the parent ApplicationContext. code example:
@Override public void Publishevent (Applicationevent event) {Assert.notnull (event, "Eve NT must not is null "); if (logger.istraceenabled ()) {Logger . Trace ( publishing event in "+ GetDisplayName () +": "+ event); } getapplicationeventmulticaster (). Multicastevent (event); if (this . Parent! = null this .parent.publishevent (event); } }
Resourcepatternresolver: Abstractapplicationcontext holds a Resourcepatternresolver instance, and the method proxy for that interface is done for that instance. code example:
@Override Public throws IOException { returnthis. Resourcepatternresolver.getresources ( Locationpattern); }
listablebeanfactory, Hierarchicalbeanfactory: Abstractapplicationcontext indirectly implements these two interfaces, but does not implement any beanfactory functionality. Abstractapplicationcontext has a configurablelistablebeanfactory instance, and all beanfactory functions are proxied to that instance. code example:
@Override Public throws beansexception { assertbeanfactoryactive (); return getbeanfactory (). Getbean (name); }
The Getbeanfactory () method of Abstractapplicationcontext is an abstract method, that is, a subclass to provide this beanfactory. code example:
@Override Public Abstract throws IllegalStateException;
In the Classpathxmlapplicationcontext inheritance system, class Abstractrefreshableapplicationcontext implements this Getbeanfactory () method. Here the Getbeanfactory () method creates a Defaultlistablebeanfactory instance as the return value.
Summary
Based on the applicationcontext of Spring Framework, this paper analyzes the mechanism and function of ApplicationContext. Interface ApplicationContext inherits a number of interfaces to meet the common functional requirements of "interface-oriented programming" in applications. Abstract class Abstractapplicationcontext implements the simple and hard-to-change part of the ApplicationContext interface, and then, by "combination", the many "easy-to-change" functions are delegated to some of its member variables, Finally, using the template method pattern allows the subclass to provide some function support for the parent class or to replace the above member variables of the parent class, thus implementing the design principle of "open for extension, closed for modification", which provides the spring framework with strong and extensible architecture support.
"Original article, reprint please specify the source" "This address" http://www.cnblogs.com/zffenger/p/5813470.html
"Spring Source Analysis series" ApplicationContext Related Interface Architecture analysis