This article mainly analyzes the design concept of the bone architecture of the Spring framework of the Spring framework. What are the core components? Why do these components need these components? How do they combine together to form Spring's skeletal architecture? How does Spring's AOP feature use these basic skeletal architectures to work? What kind of design models are used in Spring to complete this design? What is its inspiration of this design concept to our future software design? This article will answer these questions in detail.
Spring's skeletal architecture
There are more than a dozen components in Spring, but there are only a few real core components. Below is the overall architecture of the Spring framework:
Figure 1. The overall architecture diagram of theSpring framework
It can be seen from the above figure that there are only three core components in the Spring framework: Core, Context, and Beans. They build the entire Spring skeletal architecture. Without them, it is impossible to have the characteristics of the upper layers such as AOP and Web. Below will also analyze Spring mainly from these three components.
Spring's design concept
As mentioned earlier, the three core components of Spring are introduced. If the core is selected in the three of them, it must be the Beans component. Why is this that Spring is actually a programming for Bean (BOP, Bean Oriented Programming), Bean is the real protagonist in Spring.
Bean's role in Spring is just like Object's meaning to OOP. The concept of no object is like no object -oriented programming. Without the meaning of Spring in Spring. Just like a performance stage, but there are no actors. Why is the role bean or why is it so important in Spring? This is determined by the design goals of the Spring framework. Why is Spring so popular? What is the reason for our Spring? He can let you manage the dependence between objects and manages the configuration file, which is his dependency injection mechanism. And this injection relationship is managed in a IOC container, then what is the object of the IOC container is wrapped by Bean. Spring is the purpose of managing these objects and some additional operations by packing objects in Bean.
Its design strategy is completely similar to the design concept of Java to implement OOP. Of course, the design of Java itself is much more complicated than Spring, but they all build a data structure. Let it design a series of information with other individuals in this environment in this environment in accordance with certain rules. Thinking about it, think about the other frameworks we use in a large similar design concept.
How to work together with core components
As mentioned earlier, bean is a key factor in Spring. What is the role of Context and Core? If you are a actor in a performance, Context is the stage background of this performance, and Core should be the props of the performance. Only when they are together can they have the most basic condition that can perform a good show. Of course, the most basic conditions can not make this performance stand out, and the show he performs is sufficiently exciting. These programs are the characteristic functions that Spring can provide.
We know that bean is packaged is Object, and Object must have data. How to provide this data with the living environment is the problem that Context is solved. For Context, he just wants to discover the relationship between each bean and build this relationship for them And to maintain this relationship. So Context is a collection of Bean relationship. This relationship collection is also called IOC container. Once this IOC container is established, Spring can work for you. So what is the use of the Core component? In fact, Core is some columns required for the relationship between each bean to discover, establish, and maintain the relationship between each bean. From this perspective, the Core component is called Util to make you understand.
They can be represented by the figure below:
Figure 2. Three component relationships
Detailed explanation of core components
Here we will introduce the hierarchical relationships of each component in detail, as well as the order order at runtime. We should pay attention to using Spring.
Bean component
The importance of the Bean component to Spring has been explained earlier. Let's see how the component is designed. Bean components are packaged under Spring's ORG.SpringFramework.beans. All the categories under this package solve three things: Bean's definition, Bean's creation, and analysis of Bean. For Spring users, the only thing that needs to be caring is the creation of Bean. The other two are done by Spring internally, which is transparent for you.
SpringBean's typical factory model was created. His top interface is BeanFactory. The following figure is the inheritance level of this factory:
Figure 4. The inheritance relationship of thebean factory
BeanFactory has three subclasses: ListableBeanfactory, HierarchicalbeanFactory, and Autowire Capable Bean Factory. But from the above figure, we can find that the final default implementation class is defaultListableBeanFactory, and he implements all interfaces. So why define so many levels of interfaces? Check out the source code and instructions of these interfaces. It is found that each interface has an occasion that he uses. It is mainly to distinguish the restrictions of the object's data access during the transmission and conversion process of the object during the operation process of the operation process. For example, the ListableBeanFactory interface indicates that these beans are listable, and HierarchicalBeanFactory means that these beans have inheritance relationships, that is, each bean may have a father bean. AutowireCapableBeanFactory interface defines Bean's automatic assembly rules. These four interfaces jointly define the collection of Bean, the relationship between bean, and Bean behavior.
Bean's definition mainly includes Beandefinition description. As shown in the figure below illustrates the hierarchical relationship:
Figure 5. The class hierarchical relationship diagram defined bybean
The definition of Bean is a complete description of all information in the nodes you defined in the configuration file of Spring, including various sub -nodes. When Spring successfully analyzed a node you defined, he was transformed into a Beandefinition object within Spring. All operations will be done for this object in the future.
Bean's analysis process is very complicated, and the function is divided into detail, because there are many places to be extended here, and they must ensure sufficient flexibility to cope with possible changes. Bean's analysis is mainly to analyze the Spring configuration file. This analysis process is mainly completed through the class in the figure below:
Figure 6.Bean's analytical class
Of course, there are also specific analysis of TAG. It has not been listed here.
Context component
Context is packaged under Spring's ORG.SpringFramework.Context. It has explained the role of Context components in Spring. He actually provides a runtime environment for Spring to save the state of each object. Let's take a look at how this environment is built.
ApplicationContext is the top parent class of Context. In addition to the basic information of a application environment, he also inherited five interfaces. These five interfaces mainly expand the function of Context. Below is the structure diagram of Context:
Figure 7.Context -related class structure diagram
It can be seen from the figure above that the ApplicationsContext inherits BeanFactory, which also shows that the main object of the Spring container is Bean. In addition It will be explained in detail in the core.
The subclasses of ApplicationContext mainly include two aspects:
ConfigurableApplicationContext indicates that the Context is modified, that is, the user can dynamically add or modify the existing configuration information in the Context. There are multiple subclasses under it. The most commonly used Context, which is ABSTRACTREFREShableApplicat IonContext class.
WebapplicationContext is the name of the name, which is the Context prepared for the web. He can directly access the serviceContext. Usually, this interface is used less.
Then the sub -down is to construct the type of Context, followed by the way to access Context. Such a first -level level constitutes a complete Context level level.
In general, the ApplicationContext must complete the following:
◆ Make a application environment
◆ Use BeanFactory to create the Bean object
◆ Save the object relationship table
◆ Can capture various events
As a Spring IOC container, Context basically integrates most of Spring's features, or is the basis of most features.
Core component
Core components, as the core component of Spring, contain a lot of key categories. One of the important components is to define the method of access to resources. This way to abstract all resources into an interface is worth learning in future design. Let's take a look at the role of this part in Spring.
The figure below is the structural diagram related to Resource related:
Figure 8.Rsource related class structure diagram
It can be seen from the figure above that the Resource interface encapsulates various possible resource types, that is, the difference in file type is blocked for users. For the provider of resources, how to pack resources to other people to use it is also a problem. We see that the Resource interface inherits the InputStreamsource interface. This interface has a GetinPutStream method, which returns the InputStream class. In this way, all resources can be obtained through the INPUTSTREAM class, so the provider of resources is also shielded. Another problem is that the problem of loading resources, that is, the loader of the resources must be unified. From the figure above, it can The interface can load all resources, and his default implementation is the defaultResourceLoader.
Let's take a look at how Context and Resource have established a relationship? First look at the diagram of their relationship:
Figure 9. The relationship diagram ofContext and Resource
As can be seen from the figure above, Context entrusts the work of loading, analysis, and description of resources to the ResourcePatternResolver class to complete. He is equivalent to a connector. use. There are many similar ways to Core components.
How to work in IOC container
As mentioned earlier, the structure and interdependence of Core components, Bean components and context components. Here are how they run from the user's perspective, and how we let Spring complete various functions. How did it come, the following.
How to create a BeanFactory factory
As described in Figure 2, the IOC container is actually a BEAN relationship network combined with the other two components. How to build this relationship network? The built -in entrance is in the REFRESH method of AbstractApplicationContext class. The code of this method is as follows:
List 1.abstractApplicationContext.refresh
Public void refresh () throws beansexception, illegalStateException {synchronized (this.StartupShutdownMonitor) {// Prepare this context for refreshing. PRES paraRefresh (); // Tell the subclass to refresh the internal bean faction. Prepare The Bean Factory for USE in this context. PreparebeanFactory (BeanFactory); Try {// allows post-processes of the bean factor in context subclasses. StProcessBeanfactory (BeanFactory); // Invoke Factory Processors Registered As Beans in & Nbsp; The Context. InvokebeanFactoryPostProcessors (BeanFactory); // Register Bean Processors Thatpt Bean Crea Tion. RegisterBeanpostProcessors (BeanFactory); // Initial ze Message Source for this Context. InitmessageSource (); // Initialize event multicaster for this context. InitApplicationEventMulticaster (); // Ialize Other Special Beans in Specific Contex T Subclasses. Onrefresh (); // Check for Listener Beans and Register Them. RegisterListeners (); // Instant; -lazy-init) Singletons. FinishbeanFactoryinitialization (BeanFactory); // Last Step : publish corresponding event. Finishrefresh ();} Catch (Beansexception EX) {// Destroy Alream Created Singletons to Avoid Dangl Ing Resources (); // reset 'active' flag. Cancelrefresh (ex); // Propagate Exception to Caller. Throw ex;}}}This method is to build a complete code for the entire IOC container process, and understand that each line of code inside basically understands the principles and functions of most Spring.
This code mainly contains such steps:
◆ Build BeanFactory in order
◆ Event may be interested in registration
◆ Create a bean instance object
◆ Triggering events listening to
Below combined with code analysis of these processes.
The second and third sentence is to create and configure the BeanFactory. This is Refresh, that is, refresh the configuration. As mentioned earlier, the Context has a updated subclass. This is exactly this function. When the BeanFactory exists, it will be updated. The following is the method code for updating the BeanFactory:
List 2. AbstractRefreshableApplicationContext. RefreshbeanFactory
Protected Final Void RefreshBeanfactory () Throws Beansexception {if (HasbeanFactory ()) {Destroybeans (); CloseBeanfactory ();} Try { blebeanFactory Beanfactory = CreatebeanFactory (); BeanFactory.setSerializationid (getid ()); CustomizebeanFactory (BeanFactory); BeanFactory); Synchronized (this.BeanFactoryMonitor) {this.beanFactory = BeanFactory;} Catch (IOEXCEPTION Ex) {Throw New ApplicationContextexcexce PTION ("I/O ERROR & Nbsp; Parsing Bean Definition Source for" + GetdisplayName (), EX);} }This method realizes the abstract method of ABSTRactApplicationContext RefreshbeanFactory. This code clearly illustrates the creation process of BeanFactory. Note that the types of BeanFactory objects have a variety of types of types of objects. Under what circumstances, it is very important to use different subclasses. The original object of BeanFactory is the defaultListableBeanFactory. This is very important because he designed a variety of operations facing the object later. Let's take a look at the inheritance level diagram of this class:
Figure 10.DefaultListableBeanfactory class inheritance diagram
In addition to the Beanfactory -related class, it was found that it was also related to the register of Bean. In the RefreshBeanFactory method, there is a line of LoadBeandefinitions (BeanFactory) that will find the answer. This method will begin to load and analyze the definition of Bean, that is, transform the user -defined data structure into a specific data structure in IOC containers.
This process can be explained in the following sequential map:
Figure 11. Create the time preface of the beanFactory
Bean's analysis and registration process is as follows:
Fig
After creating the BeanFactory, add some tool classes needed by Spring itself. This operation is completed in AbstractApplicationContext.
The next three -line code in ABSTRACTApplicationContext play a vital role in the expansion of Spring's function. The first two lines are mainly allowed to modify the configuration of the built -in BeanFactory now. The latter line is that you can add some custom operations when you can add an instance object in the future. So they all extend the function of Spring, so we must learn to use this part of using Spring.
Among them, in the InvokeBeanFactoryPostProcessors method, it is mainly to obtain subclasses to implement BeanFactoryPostProcessor interface. And execute its postProcessbeanfactory method, the statement of this method is as follows:
Listing 3.beanFactoryPostProcessor.postProcessBeanfactory
Void PostProcessBeanFactory (ConfigurableListableBeanFactory BeanFactory) Throws Beansexception;
Its parameters are BeanFactory, indicating that it can be modified by BeanFactory. Here, this BeanFactory is a type of ConfigurableListableBeanFactory. This also confirms the different occasions used by different BeanFactory introduced earlier. This can only be configured Beanfactory to prevent some data from being being data. Users modify them at will.
The registerBeanpostProcessors method can also obtain a subclass of the user definition of the BeanPostProcessor interface and execute them to the BeanPostProcessors variable in the BeanFactory object. The two methods are declared in the BeanPostProcessor: PostProcessBeForeinitialization and PostProcessAFTERINILIZATION are used to execute during the initialization of the Bean object. Can perform user -defined operations.
The latter line code is the registration of the initialization of the monitoring event and the other listeners of the system. The listener must be the subclass of the ApplicationListener.
How to create a bean instance and build the relationship network of the bean
The following is the instantiated code of Bean, which starts with FinishbeanFactoryInitity method.
Listing 4.abstractApplicationContext.finishbeanfactoryinitialization
Protected Void FinishbeanFactoryinitialization (ConfigurawListableBeanFactory BeanFactory) {// Stop using the tempossloader for type matching. Beanf. Beanf. Actory.SettempClassLoader (NULL); // Allow for Caching All Bean DEFINITION METADATA, Not Expecting FURTHER CHANGES. nstantiate all remaining (non-lazy-init) Singletons. Beanfactory.preinstantiatedletons ();}It can be found that the instance of Bean can be found in the BeanFactory. The code of the PreINSTANTIATESINGLETONS method is as follows:
List 5.DefaultListableBeanfactory.preinstantialSINGLETONS
Public Void PreINSTANTIATESINGLETONS () Throws Beansexception {if (this.logger.isinfoenabled ()) {this.logger.info ("Pre-Instantiating Singletons in"; } Synchronized (this.beandefinitionMap) {for (string beanname: this: this .beandefinitionNames) {rootBeandefinition BD = getMergedLocalbeandefinition (Beanname); if (! Bd.isabstract () &&ISSINGLEON () &&! ()) {if (IsfactoryBean (Beanname)) {Final FactoryBean Factory = (FactoryBean) GetBean (Factory_bean_prefix+ Beanname); Boolean ISEAGERINIT; if (System.getSecurityManager ()! = Null &&; Factoryof SmartFactoryBean) {Isea GERINIT = AccessController.doprivileged (& NB SP; New PrivilegedAction <Boolean> () {& nb sp; ) {RETURN ((SmartFactoryBean) factor). IiseagerInit (); & NB sps, getAcce SSControlContext ()); ctoryBean & nb spsp; && ((SmartFactoryBean) factor). IISEAGERINIT (); if (ISEAGERINIT) {getbean (beanname);}} else {getBean (beanname);}}}}}}}}There is a very important bean here -FactoryBean. It can be said that the function of most of Spring's expansion is related to this bean. This is a special bean. He is a factory bean. Examples, if a class inherits the FactoryBean user, it can define the method of generating an instance object as long as his GetObject method is implemented. However, the instance object of this Bean inside Spring is FactoryBean. By calling the object's GetObject method, you can obtain the user's customized object, thereby providing good scalability for Spring. The object of Spring's obtaining FactoryBean itself is completed with & to complete.
How to create an instance object of the Bean and how to build a core key in the associated relationship between the Bean instance objects, the following is the flowchart of this process.
Figure 13.bean instance creation flow chart
If it is an ordinary bean, he creates his instance directly, by calling the getbean method. The following is the time -sequential map of creating a bean instance:
Figure 14.Bean instance creation sequential chart
Another very important part is to establish the relationship between the Bean object instances. This is also the core competitiveness of the Spring framework. When, how to build the relationship between them, please see the following sequential map:
Figure 15.bean object relationship establishment
Expansion point of IOC container
Another problem is how to make these bean objects have a certain extensibility, that is, some operations can be added. So what are the extensions? How does Spring call these extensions?
For Spring's IOC container, there are so many. BeanFactoryPostProcessor, BeanpostProcessor. They are called when constructing BeanFactory and building Bean objects. There are InitializingBean and DisposableBean. They are called when they are created and destroyed by the Bean instance. Users can implement the method defined in these interfaces, and Spring will call them at appropriate time. Another is FactoryBean. He is a special bean, which can be controlled by users more.
These expansion points are usually where we use Spring to complete our specific tasks. How to proficient in Spring depends on whether you have mastered what extensions Spring have, and how to use them. To know how to use them, they must understand their inherent mechanisms. You can use the following metaphor to explain.
We compare the IOC container to one box. This box has several models of the ball. You can use these molds to create many different balls. There is also a machine -made machine. This machine can produce ball models. Then their corresponding relationship is BeanFactory is the machine making model, the ball mode is Bean, and the ball of the ball mode is the instance of the bean. Where are the extensions mentioned earlier? BeanFactoryPostProcessor corresponds to the creation of a ball model, and you will have the opportunity to make a correction of it, that is, he can help you modify the ball mode. InitializingBean and DisposableBean are at the beginning and end of the ball models, and you can complete some preparations and tailing work. BeanpostProcessor allows you to make appropriate corrections to the ball mode. Finally, there is a FactoryBean, which is a magical ball model. This ball mode is not in advance, but you will determine its shape for him. Since you can determine the shape of this ball model, of course, the ball he created must be the ball you want, so in this box Reni can find all the balls you want
How to use the IOC container for me
The previous introduction of the construction process of the Spring container, what can Spring do for us, and what can Spring's IOC container do? We must first build an IOC container using Spring. Without its Spring cannot work, ApplicatonContext.xml is the default configuration file of the IOC container. All the characteristics of Spring are based on this IOC container, such as the AOP to be introduced later.
IOC is actually building a Rubik's Cube for you. Spring has set up a skeletal architecture for you. What a good thing can this Cube can come out? This must have your participation. So how do we participate? This is what I said earlier to understand some extensions in Spring, and we change the common behavior of Spring by achieving those extended points. As for how to achieve the expansion point to get the personality results we want, there are many examples in Spring. Among them, the implementation of AOP is that Spring itself has achieved its extension point to achieve the characteristic function it wants, which can be used for reference.
Detailed explanation of AOP features in Spring
The principle of implementation of dynamic proxy
To understand Spring's AOP, the principle of dynamic agency must be understood first, because AOP is implemented based on dynamic proxy. The dynamic agent must start with JDK itself.
There is a Proxy class under JDK's java.lang.reflet package, which is the entrance to the agency class. The structure of this class:
Figure 16.proxy structure structure
From the picture above, the four are public methods. The last method NewProxyinstance is the method of creating proxy objects. The source code of this method is as follows:
List 6.proxy.newproxyinstance
Public Static Object NewProxyinstance (Classloader Loader, Class> [] Interfaces, InvoCatchhandler H) Throws iLlegalagumentexception {if (h == NULL) {th row new nullpointerexception ();} Class Cl = GetProxyClass (loader, interfaces); TRY {Constructionor Cons = cl.getConStructor (constructorParams); Return (Object) Cons.newinstance (new object [] {h}); ROR (e.tostring ());} catch (illegalaccessException E) {Throw New Internet (e.tostring ());} Catch (InstantiationException E) {Throw New Internet (E.Tostring ());} Catch New Internet (e.tostring ());}}This method requires three parameters: ClassLoader, which is used to load the proxy class Loader class. Usually this loader and the agent class are the same loader class. Interfaces is those interfaces to be represented. Invocationhandler, it is used to execute the operation of users who are customized by users in addition to the methods in the proxy interface. He is also the ultimate goal for users to need to be agent. The user calls the target method is represented by the unique method defined in the InvacationHandler class Invoke. This will be explained in detail later.
Let's see how proxy produces the proxy class. What exactly does the agent class he constructed? It is revealed below.
Figure 17. Create proxy objects
In fact, it can be found from the above figure that the agent class is in the method of the GenerateProxyClass of ProxyGenerator. The Proxygientor class is wrapped under sun.misc. If you are interested, you can see his source code.
If there is such an interface, as follows:
List 7. simpleproxy class
public interface simpleProxy {public void sizeMethod1 (); public void simplemethod2 ();}The class structure generated by the agent is as follows:
List 8. $ PROXY2 Class
Public Class $ Proxy2 EXTENDS JAVA.LANG.Rang.REFLECT.Proxy Implements SimpleProxy {java.lang.reflect.method m0; java.lang.reflect.method m1; java.lang. Reflect.method m2; java.lang.reflect.method M3 ; java.lang.reflet.Method m4; int HashCode (); Boolean equals (java.lang.object); java.lang.string tostring (); void simpleMethod1 (); void Method2 ();}The method in this class will call the Invoke method of InvocationHandler, and each method will correspond to a property variable. This attribute variable M will also pass to the Method parameters in the Invoke method. This is how the entire agent is realized.
How to achieve springaop
From the principle of the previous agent, we know that the purpose of the proxy is that when the target method is called, we can execute the INVOKE method of the INVOCATIONHANDLER class, so how to make an article on InvoCationHandler is the key to implementing AOP.
Spring's AOP implementation is an agreement to comply with the AOP alliance. At the same time, Spring has expanded it, adding some interfaces such as PointCut and Advisor to make it more flexible.
Below is a class diagram of the JDK dynamic proxy:
Figure 18.jdk dynamic proxy class diagram
The picture above clearly shows the interface defined by the Aop Alliance definition. Let's not discuss how Spring expands AOP Alliance. Let's first look at how Spring realizes the agent class. To achieve the agent class, it is usually a bean in the configuration file of the Spring, as follows: as follows:
List 9. Configure proxy bean
<bean id = "testBeansingleton"> <property name = "proxyinterfaces"> <value> org.Springframework.aP.framework.prototypettests $ TESTBEAN VALUE> P Roperty> <Property name = "target"> <ref local = "testBeantarget"> Ref> Property> <Property name = "Singleton"> <Value> TrueValue> Property> <Property name = "interceptors"> <list> <Value> TestInterceptorValue> <Val UE> TestInterceptor2value> List> Property> Bean>
In the configuration, see that the interface of the agent is set, the implementation class of the interface is the target class, and the interceptor is called before executing the target method. The various interceptors defined in the Spring here can choose to use it. Essence
Let's see how Spring completes the agent and how to call the interceptor.
As mentioned earlier, Spring AOP also achieves its own expansion point to complete this feature. From this proxy class, it can be seen that it inherits the ProxyFactoryBean of Factory Bean. method. Of course, the proxy object should be dynamically generated through the Proxy class.
The following is the timing chart of the proxy object created by Spring:
Figure 19. The emergence of the object object
After Spring creates a proxy object, when you call the method on the target object, you will be represented in the Invoke method of the Invocationhandler class, which has been explained earlier. Here the JDKDynamicaopproxy class implements the InvoCationHandler interface.
Let's take a look at how Spring calls the interceptor. The following is the timing chart of this process:
Figure 20.Spring calls the interceptor
The above is the JDK dynamic agent. Spring also supports a CGLIB agent. If you are interested in seeing yourself.
Design mode analysis in Spring
There are also many design patterns used in Spring, such as factory mode, singles mode, template mode, etc., in "The System Architecture and Design Model of the WebX Framework", "Tomcat's System Architecture and Mode Design Analysis", it is already introduced. Implicate. Here we mainly introduce the agency mode and strategy mode.
Proxy mode
Proxy mode principle
The proxy mode is to create an proxy object for a certain object, and the proxy object controls the reference to the original object, and the creation of this proxy object can add some additional operations to the original object. Below is the structure of the proxy mode:
Figure 21. The structure of the proxy mode
Subject: Abstract theme, it is an interface to realize the real object of the agent object. Of course, this can be a composition of multiple interfaces.
Proxysubject: In addition to the interface of the definition of abstract themes, the proxy class must also hold a reference of the agent object
Realsubject: The class of the agent is the target object.
How to implement the proxy mode in Spring
The JDK dynamic agent in Spring Aop is achieved by using agency mode technology. In addition to the interface of the proxy object in Spring, there will also be org.springFramework.aop.springProxy and ORG.SpringFramework.aPork.advise. The constructor of using the proxy mode in Spring is as follows:
Figure 22. The structural diagram of the proxy mode is used in wiring
$ Proxy is the proxy object created, and the Subject is an abstract theme, and the proxy object is to hold a reference to the target object through Invocationhandler.
A real proxy object structure in Spring is as follows:
List 10 proxy object $ proxy4
Public Class $ PROXY4 EXTENDS JAVA.LANG.REFLECT.Proxy Implements ORG.SpringFramework.aP.framework.prototypetTestS $ TESTBEAN Work.aop.SpringProxy org.SpringFramework.aop.framework.advned {java.lang.reflecthod M16; java.lang.reflect.method m9; java.lang.reflect.method m25; java.lang.reflecthod M5; java.lang.reflecthod m2; java.lang.reflecthod M2 3; java.lang.reflet .Method m18; java.lang.reflet.Method M26; java.lang.reflect.Method M6; java.lang.reflect.method m28; java.lang.reflethod m14; java.lang. Reflect.method m12; java . Lang.reflet.Method M27; java.lang.reflect.method m11; java.lang.reflect.method m22; java.lang.reflect.Method m3; java.lang.reflect.Method java.lang.reflect. Method m4; java.lang.reflet.method m19; java.lang.reflect.Method M7; java.lang.reflet.method m15; java.lang.reflet.method m20; left.Method M10; java. LANG.Reflect.Method M1; java.lang.reflect.Method M17; java.lang.reflect.Method M21; java.lang.reflect.Method m0; ava.lang.reflet.method m24; int HashCode (); int indexof (org.SpringFramework.aop.advisor); int interxof (org.aopalliance.aip.advice); ject); java.lang.string tostring (); void sayhello (); void dosomething (); void dosometHing2 (); java.lang.class getProxiedIndIndIndIndIndIndIRFACES (); ProxytargetClass (); Org.SpringFramework.aop.advisor; getadvisors (); void addvisor (int, org.springframework.aip.advisor) Throws org.SpringFramework.aP.framework.aPConfigeXception; void addadvisor (ORG.Sprin gframework.aop.advisor) Throws org.SpringFramework.aop.framework.aPConfigeXception; void SetTargetsource (ORG .springframework.aop.targetsource); ORG.SpringFramework.aop.Targetsource GetTARGETSource (); d (); Boolean IsinterfaceProxied (java.lang.class); Boolean Removeadvisor (org.SpringFramework.aP.advisor );; Boolean SOR, ORG.SpringFramework.aP.Advisor) Throws org.SpringFramework.aop.framework.aPConfigeXception; void addAdvice (ORG.AOPALLIANCE.AOP.ADVICE) Throws org.SpringFramework.aP.framework.aPConfigexception; void addvice (int, org.aopalliance.aop.advic e) Throws org.Springframework.aP.framework.aPConfigeXception; .aop.advice); java.lang.string toproxyconfigstring (); Boolean isfrozen (); void setexposeProxy (Boolean);Strategy mode
Strategic mode principle
The strategy model, as the name suggests, is a strategy to do something. This usually means that there may be multiple methods to complete a certain operation in programming. These methods may have different occasions and may have different adaptation. However, these methods may be used. One operation method is used as an implementation strategy, and users may choose the right strategy as needed.
Below is the structure of the strategic mode:
Figure 23. Structure of strategic mode
Context:使用不同策略的环境,它可以根据自身的条件选择不同的策略实现类来完成所要的操作。它持有一个策略实例的引用。创建具体策略对象的方法也可以由他完成。
◆Strategy:抽象策略,定义每个策略都要实现的策略方法
◆ConcreteStrategy:具体策略实现类,实现抽象策略中定义的策略方法
◆Spring中策略模式的实现
◆Spring中策略模式使用有多个地方,如Bean定义对象的创建以及代理对象的创建等。这里主要看一下代理对象创建的策略模式的实现。
前面已经了解Spring的代理方式有两个Jdk动态代理和CGLIB代理。这两个代理方式的使用正是使用了策略模式。它的结构图如下所示:
图24.Spring中策略模式结构图
在上面结构图中与标准的策略模式结构稍微有点不同,这里抽象策略是AopProxy接口,Cglib2AopProxy和JdkDynamicAopProxy分别代表两种策略的实现方式,ProxyFactoryBean就是代表Context角色,它根据条件选择使用Jdk代理方式还是CGLIB方式,而另外三个类主要是来负责创建具体策略对象,ProxyFactoryBean是通过依赖的方法来关联具体策略对象的,它是通过调用策略对象的getProxy (ClassLoaderclassLoader)方法来完成操作。
Summarize
本文通过从Spring的几个核心组件入手,试图找出构建Spring框架的骨骼架构,进而分析Spring在设计的一些设计理念,是否从中找出一些好的设计思想,对我们以后程序设计能提供一些思路Essence接着再详细分析了Spring中是如何实现这些理念的,以及在设计模式上是如何使用的。