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

Source: Internet
Author: User

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

使用Transaction类来模拟事物管理,代码如下:public class Transaction {//模拟开启事务public void beginTransaction() {System.out.println("开启事务");}//模拟提交事务public void commit(){System.out.println("提交事务");}}使用Login类来模拟登录这个业务,代码如下:public class Login {private Transaction transaction;//模拟用户登录public Login(Transaction transaction) {this.transaction = transaction;}//模拟登录这个业务操作public void login() {transaction.beginTransaction();System.out.println(“验证用户名和密码是否合法”)transaction.commit();}}


4.1 Test

使用Client来模拟客户端用户触发登录事件,代码如下:public class Client {//模拟客户端用户触发登录事件@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.

使用Logger类来模拟日志处理功能,代码如下:public class Logger {public void logging() {System.out.println("logging");}}但是我们很快发现Login类也必须做出改变如下:public class Login {private Transaction transaction;//增加loggerPrivate Logger logger;//模拟用户登录public Login(Logger logger,Transaction transaction) {this.logger = logger ;this.transaction = transaction;}//模拟登录这个业务操作public void login(String username, String password) {transaction.beginTransaction();System.out.println(“验证用户名和密码是否合法”);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

按照Spring AOP的语言规范,Transaction类来模拟事物管理切面,代码同3.4OOP实现的Transaction。Logger类来模拟日志处理切面,代码同3.4OOP实现的Logger。其中Transaction和Logger就是AOP中的切面,beginTransaction() ,commit()和logging()方法就是AOP中的通知。核心业务关注点实现:public class Login {//模拟登录这个业务操作public void login() {System.out.println("验证用户名密码的合法性");}}

5.3 reorganization of concerns

实际上编织的过程,是由Spring AOP框架来实现,我们只需要告诉Spring AOP框架,Spring AOP框架自动为我们做这些工作,而不用我们自己编写代码实现。我只需要在配置文件(.xml)中做配置即可。配置文件代码如下:<?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、引入AOP的命名空间2、目标类3、切面4、拦截器  由spring内部实现5、aop的配置 --><bean id="transaction" class="cn.miao.login.aop.cglib.Transaction"></bean><bean id="login" class="cn.miao.login.aop.cglib.Login"></bean><!-- aop的配置 --><aop:config><!-- 切入点表达式  expression     确定哪个类可以生成代理对象  id  唯一标识  --><aop:pointcut expression="execution(* cn.miao.login.aop.cglib.Login.*(..))" id="perform"/><!-- 切面 --> <aop:aspect ref="transaction"> <!--  前置通知   *  在目标方法执行之前   *    --> <aop:before method="beginTransaction" pointcut-ref="perform"/> <aop:after method="commit" pointcut-ref="perform"/> </aop:aspect></aop:config></beans>

5.4 Test

测试代码:@Testpublic void testLogin() {ApplicationContext context = new ClassPathXmlApplicationContext("cn/miao/login/aop/cglib/applicationContext.xml");Login login = (Login) context.getBean("login");login.login();}运行结果:开启事务验证用户名密码的合法性提交事务

5.5 demand changes

当然我们假设出现和4.4 OOP实现相同的变更,这时我们需要加入日志功能。这时我们只需要增加Logger类同OOP实现。并在配置文件中增加如下信息:<bean id="logger" class="cn.miao.login.aop.cglib.change.Logger"></bean><aop:aspect ref="logger"> <!--  前置通知   *  在目标方法执行之前   *    --> <aop:after method="logging" pointcut-ref="perform"/></aop:aspect>是不是很方便,只需要扩张,而无需对代码进行变更。这就是AOP在处理类似切面上优势。

6 aspectj implementation

实现Login类同4.4 Spring AOP实现。事务处理类Transaction是一个切面如下:public aspect Transaction {//切入点pointcut beginTransaction() : execution(* cn.miao.login.aop.aspectj.Login.login(..));//前置通知before() : beginTransaction() {System.out.println("开启事务");}pointcut commit() : execution(* cn.miao.login.aop.aspectj.Login.login(..));//后置通知after() : commit() {System.out.println("提交事务");}}

测试/***在运行前需要先用ajc命令编译*/public class Client{public static void main(String []args) {Login login = new Login();login.login();}}运行结果:开启事务验证用户名密码的合法性提交事务

需求变更增加切面Logger。public aspect Logger {pointcut logging() : execution(* cn.miao.login.aop.aspectj.change.Login.login(..));after() returning() : logging() {System.out.println("logging");}}测试客户端不需要做任何变动,在运行前需要重新编译。运行结果如下:开启事务验证用户名密码的合法性logging提交事务

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 [email protected]. 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





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

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.