Application and Research of AOP technology -- simple application of AOP and Application of aop technology -- aop

Source: Internet
Author: User

Application and Research of AOP technology -- simple application of AOP and Application of aop technology -- aop

In order to better understand AOP practices and reflect the advantages of AOP, we will always compare OOP with AOP in the following sections. In the end, we will summarize the advantages of AOP compared with OOP, the disadvantages of AOP, and the general use cases of AOP.

 

1.1 ing between question space and solution space

Before comparing OOP and AOP practices, let us first solve the differences between theoretically OOP and AOP in solving problems, that is, their different mappings from the problem space to the solution space.

1.1.1 Definitions of "problem space" and "solution space"

The definitions in different documents are slightly different. The definitions in this article are as follows:

Problemspace)It is a domain formed by the analysis and abstraction of problems relative to the domain of solution.

Solutionspace)Is the implementation of problems in the field [2].

Software development always generates a software that can meet the requirements to solve one or more specific problems, therefore, it can be roughly abstracted into the ing process from problematic space to solution space. Therefore, demand analysis is naturally a problem space. We classify system analysis, design models, and programs as solutions. The ing between the problem space and the solution space is different, which is the fundamental difference between AOP and OOP.


1.1.2 problem space to solution space ing in OOP

The problem space is mapped to the solution space in multiple dimensions to one dimension. OOP allows us to regard the system as a group of objects of mutual cooperation. Class allows us to hide implementation details under the interface. Polymorphism provides public behaviors and interfaces for related concepts, and allows specific components to change specific behaviors without having to access basic implementations. However, OOP Technology maps the natural world in the problematic world to the basic unit of "class". After a class implements an interface, it cannot implement another interface dynamically, the behavior of existing classes is basically fixed before compilation. It is either a method defined inside the class or a method inherited from the inheritance and implementation interfaces. However, in actual programming work, we have encountered a "cross-class" situation, that is, cross-cutting concerns.


1.1.3 ing between problem space and solution space in AOP

AOP can better isolate system concerns than OOP, thus providing modular cross-cutting concerns. A complex system can be viewed as a combination of multiple concerns. A typical system may have several considerations, such as business logic, performance, data storage, log and scheduling information, authorization, security, thread, and error check, there are also concerns in the development process, such as easy to understand, easy to maintain, easy to trace, and easy to expand, so that the multi-dimensional to multi-dimensional ing process is completed (4.1)


1.1.4 Problems

OOP abstracts and encapsulates entities, attributes, and actions in the business processing process to achieve clearer and more efficient logical unit division. In terms of nouns, the focus is on the vertical relationship between objects (implemented through inheritance). Generally, the focus is on classes.
AOP extracts the aspect of the business processing process. It faces a certain step or stage in the processing process, low coupling isolation between various parts in the logical process is achieved. It is oriented to the verb field and focuses on horizontal. A segment or aspect in a logical process, such as log management and permission management. It focuses mostly on software systems. It is not the business logic that focuses more on objects. The same loose method is used to reduce the Coupling Degree between systems. Its Modular unit is the aspect.


2. AOP development steps

AOP, in essence, is to use a loose coupling method to achieve various independent concerns, and then combine these implementations to establish the final system. The system built with it is loosely coupled. Through the above analysis, we summarize the general steps of AOP software development based on the problem space to solution space and 2 AOP introduction, as shown in 4.2, the following three steps are required: (For details, refer to 4.3)


(1) decomposition of concerns. By analyzing user requirements, the module-level core business focus and system-level cross-cutting focus are extracted. In this step, we need to separate the core concerns from the system-level cross-cutting concerns. The division of cross-cutting concerns generally meets the following conditions:

L The functions implemented by the focus span multiple modules

L The focus is relatively independent from the core business and does not belong to the same problem domain

L The focus is not within the scope of the system's business functions

(2) focus on implementation. For core business logic concerns, we use the OOP method to generate various classes. For cross-concern concerns, we must use the AOP method to generate the relevant code.

(3) focus on restructuring. The reorganization process is also called weaving or weaving (for details about the weaving method). It is to use some reorganization rules to weave the aspect code into the core function code based on the 00P implementation through the aspect knitting tool. To build the final system.


3. One Actual scenario

In almost any system development in B/S mode, we will encounter login to such a module. The process of user logon involves user logon authentication to check whether the user name and password entered by the user are valid. We will use OOP and AOP to implement the login module. In the comparison of implementation methods, we will get the difference between OOP and AOP. The general steps of AOP development are as follows, it also analyzes the applicable scenarios of the AOP technology and the advantages brought by the use of the AOP technology to our system development.


4. OOP implementation

Use the Transaction class to simulate Transaction management. The Code is as follows: public class Transaction {// simulate opening the Transaction public void beginTransaction () {System. out. println ("enable transaction");} // simulates the commit transaction public void commit () {System. out. println ("Commit Transaction") ;}} use the Login class to simulate Login to this service. The Code is as follows: public class Login {private transaction Transaction; // simulate user logon to public Login (Transaction transaction) {this. transaction = transaction;} // simulate the login to this business operation public void login () {transaction. beginTransaction (); System. out. println ("Verify that the user name and password are valid") transaction. commit ();}}


4.1 Test

Use the Client to simulate a logon event triggered by a Client user. The Code is as follows: public class Client {// simulate a logon event triggered by a Client user @ Testpublic void testLogin () {Transaction transaction = new Transaction (); login login = new Login (transaction); login. login ();}}

4.2 demand changes

The above is a simple simulation implementation of the module we log on to. One day, due to the company's needs, we will record the logs of every user login, so as to facilitate security auditing in the future. Of course, software system changes are impermanence, and such assumptions are entirely possible. Although we can avoid this situation as much as possible through scientific needs, it is impossible to avoid it completely. Okay. Now we need to add the log processing function to the logon.

Use the Logger class to simulate the log processing function. The Code is as follows: public class Logger {public void logging () {System. out. println ("logging") ;}} but we soon discovered that the Login class must also be changed as follows: public class Login {private Transaction transaction; // added loggerPrivate Logger; // simulate user logon to public Login (Logger logger, Transaction transaction) {this. logger = logger; this. transaction = transaction;} // simulate logon to this business operation public void login (String username, String password) {transaction. beginTransaction (); System. out. println ("Verify that the user name and password are valid"); logger. logging (); transaction. commit ();}}

5 SpringAOP implementation

We follow the 2AOP development steps to use Spring AOP to implement the above example.

5.1 decomposition of concerns

Through analysis, we can conclude that in the login module, the core business function we want to implement is login, which is our core business function. According to the Section 4.2AOP development steps, the cross-cutting focus usually meets the following conditions. It is not difficult to find that transaction processing and log processing are not core business functions and may span other modules. Therefore, transaction processing and log processing are the cross-cutting concerns. The specific implementation is as follows:


5.2 Focus implementation

According to the language specification of Spring AOP, the Transaction class simulates the Transaction management aspect. The Code is the same as the Transaction implemented by 3.4OOP. The Logger class is used to simulate log processing. The Code is the same as the Logger implemented by 3.4OOP. Here, Transaction and Logger are the aspect in AOP, And the beginTransaction (), commit (), and logging () methods are the notifications in AOP. Core Business Focus implementation: public class Login {// simulate logon to this business operation public void login () {System. out. println ("verify the validity of the user name and password ");}}

5.3 reorganization of concerns

In fact, the process of weaving is implemented by the Spring AOP framework. We only need to tell the Spring AOP framework that the Spring AOP framework will automatically do this for us without writing our own code for implementation. I only need to configure in the configuration file (. xml. The configuration file code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <! -- 1. Introduce the AOP namespace 2. Target class 3. aspect 4. implement internal interceptor by spring 5. Configure aop --> <bean id = "transaction" class = "cn. miao. login. aop. cglib. transaction "> </bean> <bean id =" login "class =" cn. miao. login. aop. cglib. login "> </bean> <! -- Aop configuration --> <aop: config> <! -- Entry point expression determines which class can generate the unique identifier of the proxy Object id --> <aop: pointcut expression = "execution (* cn. miao. login. aop. cglib. login. *(..)) "id =" perform "/> <! -- Cut --> <aop: aspect ref = "transaction"> <! -- Pre-notification * before executing the target method * --> <aop: before method = "beginTransaction" pointcut-ref = "perform"/> <aop: after method = "commit" pointcut-ref = "perform"/> </aop: aspect> </aop: config> </beans>

5.4 Test

Test code: @ Testpublic void testLogin () {ApplicationContext context = new ClassPathXmlApplicationContext ("cn/miao/login/aop/cglib/applicationContext. xml "); Login login = (Login) context. getBean ("login"); login. login ();} running result: Start the transaction to verify the validity of the username and password and submit the transaction.

5.5 demand changes

Of course, we assume that the same change as the 4.4 OOP implementation occurs. In this case, we need to add the log function. In this case, we only need to add the Logger class to be the same as the OOP implementation. Add the following information to the configuration file: <bean id = "logger" class = "cn. miao. login. aop. cglib. change. logger "> </bean> <aop: aspect ref =" logger "> <! -- Pre-notification * Before executing the target method * --> <aop: after method = "logging" pointcut-ref = "perform"/> </aop: aspect> is it very convenient, you only need to expand without changing the code. This is the advantage of AOP in similar aspect processing.

6 AspectJ implementation

Login is similar to 4.4 Spring AOP. Transaction processing class Transaction is a plane: public aspect Transaction {// pointcut beginTransaction (): execution (* cn. miao. login. aop. aspectj. login. login (..)); // pre-notification before (): beginTransaction () {System. out. println ("enable transaction");} pointcut commit (): execution (* cn. miao. login. aop. aspectj. login. login (..)); // post-notification after (): commit () {System. out. println ("Commit transaction ");}}

Test/*** run the ajc command to compile */public class Client {public static void main (String [] args) {Login login = new Login (); login. login () ;}} running result: Start the validity of the username and password for transaction verification and submit the transaction.

The requirement change adds a Logger. Public aspect Logger {pointcut logging (): execution (* cn. miao. login. aop. aspectj. change. login. login (..)); after () returning (): logging () {System. out. println ("logging") ;}} the test client does not need to be changed and needs to be re-compiled before running. The running result is as follows: Enable the legality of the username and password for transaction authentication logging to submit the transaction

7. Differences between AOP and OOP

AOP puts forward the concept of Aspect on the basis of 00P. The difference between it and 00P is first manifested in the introduction of a brand-new perspective on the Awareness System of AOP: aspect. A system can be divided into objects one by one from the perspective of P according to the "vertical" function. AOP separates a part of the system from a "horizontal" perspective.

Secondly, in AOP, each object does not know whether it is followed by other concerns (Aspects) or how many concerns are being followed by itself. All of this information is defined in terms. On the contrary, each object knows whether or not to add a concern and how many concerns to add. That is to say, in AOP, the flow of the combination is from the cross-cutting concern to the general concern (the object itself ). The opposite is true for P. This is the main difference between AOP and 00P.

Third, in P, the function of each object is determined during the compilation or code writing phase. In AOP, The. function must be "woven" before being added to the object. Therefore, the final time for the function of an object depends on the time when the aspect is woven, which may be during the compilation or loading or runtime [16].

Although AOP was proposed after OOP and is expected to better solve the problems faced by 00P. However, AOP and 00P are not two competing technologies. We do not propose AOP to replace 00P. In fact, AOP and 00P complement each other. AOP supplemented the limitations of 00P. In fact, AOP can also

Other programming models. Like process-oriented programming. However, because 00P is the mainstream model. Therefore, most AOP tools are extended to 00 tools. People are also more keen on adding 8.1 P to AOP [16] 8 advantages of code readability

The ease of understanding in the Code set solves code confusion and code dispersion caused by OOP cross-module. At the same time, OOP implements several focuses to blur the implementation of different concerns, so that the correspondence between the concerns and their implementations is not obvious. The modules in the software system may have to take into account the needs of several aspects at the same time. For example, developers often need to consider business logic, performance, synchronization, log and security issues at the same time, taking into account the needs of various aspects, leading to the simultaneous implementation elements of the corresponding concerns, leading to code confusion, AOP can easily implement this requirement as an independent aspect, which is readable. In the preceding application example, we can easily find that in OOP implementation, the Business Method login () not only has business logic-login, but also has a lot of functional Code such as transaction processing and logging. When there are many such cross-cutting functions, the code is messy. In the AOP implementation (including Spring AOP implementation and AspectJ implementation), only the login business logic, transaction processing, logging, and other cross-cutting functions are scattered in the corresponding section, the business logic is clear and the code is naturally readable.


8.2 code Redundancy

In OOP, due to the fact that multiple modules are involved in the cross-cutting concerns, their implementations must be distributed across these modules. For example, in a database system, performance problems affect all database modules, which leads to code distribution. AOP modularize the cross-concern and process each concern with the smallest coupling, so that even the cross-concern is modularized. The Code redundancy of the system generated by such implementation is small. The modular implementation must be easily understood and maintained by the system. In the implementation of AOP, the cross-section code is public, and the code of the cross-section function only needs to be written once. In OOP implementation, if new business logic appears, there will be cross-cutting functions (such as logs) in the new business logic ), the cross-cutting code must be repeatedly written. Therefore, the implementation of AOP is much less redundant than the implementation of OOP code.

8.3 code scalability

The system is easy to expand. Because the aspect module does not know the cross-cutting concerns, it is easy to add new features to the new aspect. In addition, when a new module is added to the system, the existing aspect of automatic cross-cutting makes the system easy to expand. Designers can postpone the decision for future needs because they can easily implement this requirement as an independent aspect. In the preceding application example, we can clearly see that, when the demand changes, AOP shows good code scalability. You only need to add new sections or modify the configuration file, instead of implementing OOP, You need to modify the business logic code. AOP is well compliant with the principle of openness to extensions and closure to modifications.


8.4 code reuse rate

For better code reusability, AOP implements each aspect as an independent module, and modules are loosely coupled. For example, in the preceding application example, the Logger and Transaction planes exist as independent modules, and there is almost no coupling between them, loose coupling usually means better code reusability. AOP is better than OOP in Making System loose coupling [2, 16].


9 Conclusion

AOP was proposed on the basis of OOP, providing a very good implementation solution for the horizontal cutting function in the software system, making up for the shortcomings of OOP in solving the cross-cutting problem. The basic concepts of AOP, including Advice and Pointcut, are discussed in depth. The common AOP knitting time is studied. One is AspectJ static knitting, that is, compiling and weaving. The advantage is that the code execution is more efficient, and the disadvantage is that the code needs to be re-compiled after each code modification; the other is the Dynamic Weaving of Spring AOP, that is, code runtime knitting. The advantage is that after the code is modified, it can be deployed without the need to re-compile the code. The disadvantage is that the Code is not highly optimized, the execution efficiency is slightly lower.

The implementation of Spring AOP is mainly studied in the implementation of AOP. The first core module is the generation of AopProxy proxy objects, which is implemented by jdk dynamic proxy or cglib dynamic technology. The second core module is the call of the Spring AOP interceptor, which actually implements the call of notifications.

The AOP application adopts OOP implementation and AOP implementation (Spring AOP implementation and AspectJ implementation) through a simple login business logic, we also observed the response of the three implementation methods in response to demand changes. We found that the AOP technology and OOP technology have better code readability, redundancy, and scalability when dealing with cross-cutting logic, the four advantages of high reuse rate are as follows.

In short, the emergence of the AOP technology and various AOP languages has brought more ideological weapons and development tools to the development of our software systems, good research and utilization will bring many surprises to our software development.

 

At present, the AOP technology application and research series are planned to be six blog articles, which have been completed. See the following table for the contents. Here, the sample code of the AOP technology application and research application has been completed, and I have already shared it on github.Aop https://github.com/demiaowu/aopIf you have any errors or questions, contact your cfreestar@163.com. For more information, see the end of this document. If you have not added any information, contact us and I will modify or delete it in time.

Application and Research of AOP technology in a series of blogs






Several methods for implementing Spring AOP applications

Spring has three methods for developing aop applications: Spring 1.2 implements aop through ProxyFactoryBean, that is, dynamic proxy. Aspect must inherit MethodBeforeAdvice, MethodAfterAdvice, and so on. <! -- Proxy object --> <bean id = "man" class = "Man">
<Property name = "name">
<Value type = "java. lang. String"> JOHN </value>
</Property>
</Bean> <! -- Inherits the Aspect of the MethodBeforeAdvice class->
<Bean id = "fbi" class = "FBI"/>
<Bean id = "civilian"
Class = "org. springframework. aop. framework. ProxyFactoryBean">
<Property name = "target">
<Ref bean = "man"/>
</Property> <property name = "interceptorNames">
<List>
<Value> fbi </value>
</List>
</Property>
</Bean> 2: The FBI class is required for Spring 2.0 AOP applications, and it does not need to implement some interfaces. public class FBI {
Public void before (JoinPoint point ){
Man man = (Man) point. getTarget ();
System. err. println ("FBI found" + man. getName () + "in progress" +
Point. getSignature (). getName () + "activity. ");
}
} Note that the method before (JoinPoint) in this class can have any method name and include a JoinPoint class.
You can also write before () directly without parameters. However, this JoinPoint object brings
Information related to this method call, including method parameters and target objects.
Will carry it.
The next step is to test the class code, which is almost no different from the previous one, but now the direct access to man
This bean. <Beans xmlns = "www.springframework.org/schema/beans"
Xmlns: xsi = "... the remaining full text>
 
Examples of specific application of AOP in spring

Spring provides many features, so I will quickly display all of its main aspects in turn.

First, let's clarify the Spring scope. Although Spring covers many aspects, we already have a clear concept of what should be involved and what should not be involved.

Spring aims to make J2EE easy to use and promote programming habits.
Spring does not re-develop existing things. Therefore, in Spring, you will find packages without logging, no connection pools, and no distributed transaction scheduling. These are provided by open-source projects (such as Commons Logging for all log output, or Commons DBCP for data connection pools), or by your application server. For the same reason, we have not provided the O/R mapping layer. For this reason, there are friendly solutions such as Hibernate and JDO.
Spring
Spring aims to make existing technologies easier to use.

For example, although we do not have the underlying transaction coordination processing, we provide an abstraction layer covering JTA or any other transaction policies.

Spring does not directly compete with other open-source projects unless we feel that we can provide new things. For example, many developers have never been happy with Struts and feel that there is still room for improvement in the MVC web framework. In some fields, such as lightweight IoC containers and AOP frameworks, Spring has direct competition, but there are no more popular solutions in these fields. (Spring is a pioneer in these areas .)

Spring also benefits from internal consistency.
All developers are singing the same song, and the basic idea is still the ones designed and developed by Expert One-on-One J2EE.

In addition, we have been able to use some major concepts, such as inverted control, to deal with multiple fields.

Spring can be transplanted between application servers.
Of course, ensuring portability is always a challenge, but we avoid any specific platform or non-standardization and support users on WebLogic, Tomcat, Resin, JBoss, WebSphere, and other application servers.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.