The basic __AOP of AOP technology

Source: Internet
Author: User
Tags aop exception handling jboss jboss application server
1. The origins of AOP technology

The birth of AOP technology was not too late, and as early as 1990, researchers from Xerox Palo Alto research Lab (i.e. PARC) analyzed the limitations of object-oriented thinking. They have developed a new programming idea that may help developers improve productivity by reducing code-duplication modules. With the deepening of research, AOP has gradually developed into a complete set of program design ideas, various applications of AOP technology has emerged.

AOP technology is the first to be applied under the Java platform. At the same time as Parc's research on aspect-oriented programming, Northeastern University, a PhD candidate from the United States, Cristina Lopes and colleagues began a similar thinking. In the end, the U.S. Defense Advanced Technology Research Program (Defense Advanced study Projects Agency, DARPA) took note of the work and provided research funding to encourage the integration of the work results. By defining an extension system for the Java language, they enable developers to facilitate aspect-oriented development, a system called ASPECTJ. Later, AspectJ was transferred to Eclipse Foundation in 2002, becoming a pioneer in AOP technology in the open source community and the most popular AOP tool of all time.

Aspectwerkz is a dynamic, lightweight AOP framework based on Java. Aspectwerkz is still a product in the open source community, sponsored by BEA System, and the developer is the two employees of BEA, Jonas Bonér and Alexandre Vasseur. The most recent version is Aspectwerkz 2.0. In January 2005, ASPECTJ and Aspectwerkz agreed to combine their results to create a single tool. The first release of their collaboration was ASPECTJ 5, which expanded the ASPECTJ language to support a similar ASPECTJ code style based on annotation development style. AspectJ 5 also provides full AOP support for the language features of Java 5.

In the Java camp, the commercial software maker JBoss introduced the AOP framework and components in its 2004 release of JBoss 4.0. In JBoss 4.0, the user can use JBoss AOP separately outside the JBoss application server, which is JBoss AOP 1.0, released in October 2004. In 2005, the JBoss AOP framework was released in 1.3.0, and the new version optimizes the performance of load-time weaving (Weev) and pointcut-cut matching, greatly reducing the startup time of the application.

As a lightweight framework,spring in the development of lightweight Java EE, the application is very extensive. It implements AOP through the IOC model (inversion of control, inversion mode), which is often referred to as spring AOP. Published in 2004 as an extension of the spring framework, the current version has been updated to 1.1.3. Spring AOP as a non aggressive, lightweight AOP framework, developers need to apply AOP in Java programs without using a precompiled or other meta tag. Currently, the capabilities of AOP are fully integrated into the context of spring transaction management, logging, and various other features.

In the. NET camp, the application of AOP technology is far less than the Java camp's focus on AOP. The Enterprise Library, released by Microsoft in January 2005, offers 7 different "application blocks (Application blocks)". There are individual experts who believe that these components can be considered as aspects. But this view has not been unanimously agreed. In fact, under the. NET Platform, the driving force behind the development of AOP technology is not Microsoft, but the open source community. While Microsoft's technical experts have heard the call for an increase in AOP technology in the. Net framework, it is clearly unrealistic for such a large software company to be flexible in its strategic direction. Because of this, it gives the open source community in the research and exploration of AOP technology a huge development space.

Unlike AOP technology in the Java camp, it is currently in the. NET platform, the various AOP tools, basically remain in the lab phase. But some of the technologically leading and maturing AOP products are also emerging in the open source community. This mainly includes Aspect#,aspectdng,eos AOP and so on.

Aspect# is based on Castle dynamic agent technology. Castle originates from the Apache Avalon Project, which aims to achieve a lightweight IOC container. Aspect# was included as one of Castle's subprojects in June 2005. It is an AOP framework implemented for the CLI (. NET and mono), using mechanisms such as reflection, proxies, and so on. The current aspect# version is 2.1.1.

The current version of ASPECTDNG is 0.7, still in beta phase. Its implementation technology is based on rail static weaving. Rail belongs to the IL-level code weaving, its custom set of XML-formatted ILML language, can break the original assembly into ILML format, so as to modify and extend the static assembly, so as to achieve the purpose of static weaving. Because ASPECTDNG is a code that belongs to the IL level, it is in the. NET platform, it is not limited by the specific programming language.

Eos AOP, like aspectdng, still uses static weaving, but from a syntactic definition it is more akin to ASPECTJ implementation of AOP. It expands the C # syntax, introduces aspect, introduce, before, after, and provides a dedicated EOS compiler. The EOS project started in September 2004, and the 0.3.3 version, released in June 2005, is the latest version, with the main developers Hridesh Rajan and Kevin Sullivan. The former is a graduate student of the computer department at Virginia University, and the EOS project was originally proposed by Hridesh Rajan, while the latter was an Associate Professor (Associate professor) of the computer department. So since the beginning of Eos, there is a strong academic characteristics.

From the perspective of the overall development of AOP technology, the high performance, stable, extensible, easy-to-use AOP Framework is its trend and goal. From the above analysis of various AOP technology, AOP technology is undoubtedly common characteristics, and all kinds of implementation technology is around these commonalities in-depth and extension. Next, I will outline the nature of AOP and its technical elements. 2. AOP Technology Essentials 2.1 Technology Overview

AOP (aspect-oriented programming, aspect-oriented programming) can be said to complement and refine oop (object-oriented programing, object-oriented programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy to simulate a set of public behaviors. Oop seems powerless when we need to introduce public behavior for dispersed objects. In other words, OOP allows you to define a relationship from top to bottom, but it is not appropriate to define a relationship from left to right. such as logging functions. The log code tends to spread horizontally across all object hierarchies and has nothing to do with the core functionality of the objects it spreads to. This is true for other types of code, such as security, exception handling, and the persistence of transparency. This scattered, unrelated code is called crosscutting (cross-cutting) code, which, in OOP design, results in a lot of code duplication, which is not conducive to the reuse of each module.

AOP technology, in contrast, uses a technology called crosscutting to unpack the encapsulated objects and encapsulate the public behavior that affects multiple classes into a reusable module called "Aspect", which is the aspect. The so-called "aspect", in short, is that those who have nothing to do with the business, but for the business module of the common call of the logic or responsibility encapsulation, easy to reduce the system of duplication of code, reduce the coupling between modules, and conducive to future operability and maintainability. AOP represents a horizontal relationship, if "object" is a hollow cylinder, which encapsulates the object's properties and behavior, so the aspect-oriented programming approach, like a razor, cuts these hollow cylinders open to get inside the message. And cut the cut, which is called "aspect". Then it will be skillfully seize the hands of the hands of the cut off the cutting surface of the surface recovery, without leaving traces.

Using crosscutting technology, AOP divides software systems into two parts: core concerns and crosscutting concerns. The main process of business processing is the core concern, and the part that does not relate to it is crosscutting concerns. One of the features of crosscutting concerns is that they often occur at many points in the core focus and are basically similar in every place. such as permission authentication, log, transaction processing. The role of AOP is to isolate the various concerns in the system, separating the core concerns from the crosscutting concerns. As Adam Magee, senior architect of Avanade, says, the central idea of AOP is "to separate the business logic in the application from the generic services that provide it with support." ”

The technology to implement AOP is divided into two major categories: first, using dynamic Proxy technology, the message is decorated with the method of intercepting the message, in order to replace the execution of the original object behavior; the second is to create "aspects" by introducing a specific syntax in the form of static weaving, so that the compiler can weave the "aspects" during compilation. The code. However, the technical characteristics of AOP are the same, respectively:

1. Join Point (Junction): A precise point of execution in the execution of a program, such as a method in a class. It is an abstract concept that does not need to define a join point when implementing AOP.

2. Point Cut (pointcut): essentially a structure that captures the connection points. In AOP, you can define a point cut to capture calls to related methods.
3, Advice (notice): Is the point cut of the execution code, is the implementation of "aspects" of the specific logic.
4, Aspect (aspect): Point cut and advice combined is aspect, it is similar to a class defined in OOP, but it represents more of the horizontal relationship between objects.
5, introduce (introduction): To introduce additional methods or attributes for the object, so as to modify the object structure. Some AOP tools refer to it as mixin.

These technical features form the basic AOP technology that most AOP tools implement. They can also be the basic terminology for studying AOP technology. 2.2 crosscutting Technology

"Crosscutting" is the proper term for AOP. It is a relatively simple design and programming technology that contains powerful forces, especially when it comes to building loosely coupled, scalable enterprise systems. Crosscutting technology enables AOP to operate through established responsibilities (such as logging and performance optimization) in a given programming model.

What happens to software development if you don't use crosscutting technology? In traditional programs, because the implementation of crosscutting behavior is decentralized, it is difficult for developers to implement or change these behaviors logically. For example, the code for logging is wrapped around code that is primarily used for other responsibilities. Depending on the complexity and scope of the problem being solved, the resulting confusion can be large and small. Changing the logging policy for an application may involve hundreds of edits--even if it works, it's a daunting task.

In AOP, the behavior of these common logic intertwined with the core logic of other modules is called a crosscutting concern (crosscutting concern) because it spans the typical boundaries of responsibility in a given programming model. 2.2.1 crosscutting concerns

A concern (concern) is a specific purpose, a region of interest to us, a logical behavior that we need. From a technical standpoint, a typical software system contains some core concerns and system-level concerns. For instance, one of the core concerns of a credit card processing system is loan/deposit processing, while system-level concerns are log, transactional integrity, authorization, security, and performance issues, and many of the concerns-crosscutting concerns (crosscutting concerns)-appear in multiple modules. If you use existing programming methods, crosscutting concerns traverse multiple modules, making it difficult to design, understand, implement, and evolve the system. AOP can better isolate system concerns than the above methods, thus providing modular crosscutting concerns.

A complex system, for example, is implemented by a number of focus combinations, such as business logic, performance, data storage, log and scheduling information, authorization, security, threading, error checking, and concerns in the development process, such as understandable, easy to maintain, easy to track, easy to expand, etc. Figure 2.1 illustrates a system that consists of a number of concerns that are implemented by different modules.


By identifying the requirements and implementation of the system, we can divide the concerns in the modules into core concerns and crosscutting concerns. For core concerns, the modules that implement these concerns are, in general, independent of each other, and they complete the business logic required by the system, which is related to specific business requirements. For the concerns of logging, security, and persistence, they are the common needs of business logic modules, which are distributed throughout the core concerns. In AOP, such as these modules, are called crosscutting concerns. The key to the application of AOP crosscutting technology is to realize the recognition of attention points.

If the whole module is likened to a cylinder, then the focus recognition process can be described by the Prism law, passing through the prism beam (meaning the demand), radiating to the cylinder, getting different colors of the beam, and finally identifying the different points of attention. As shown in Figure 2.2:


Among the concerns identified above, Business logic is a core concern that calls crosscutting concerns such as security,logging,persistence.

public class Businesslogic
{public
    void someoperation ()
    {
       //authentication security; securtity concerns;
       //log before execution ; logging concern;

       dosomething ()

       ; Save the data after the logical operation; persistence attention point;
       //execute end log; logging focus;
    }

The purpose of AOP is to isolate crosscutting concerns, such as logging, from the Businesslogic class. With AOP technology, the relevant crosscutting concerns can be encapsulated to form a separate "aspect". This ensures that crosscutting concerns are reused. Because the Businesslogic class no longer contains logical code for crosscutting concerns, crosscutting techniques can be used to intercept messages for related methods in the Businesslogic class, such as the Someoperation () method, and to achieve the purpose of invoking crosscutting concerns, and then " Aspect "weaves into the method. For example, figure 2.3:


Through the use of AOP technology, the design of the whole system has been changed. At the beginning of the analysis of system requirements, the idea of AOP was used to isolate the core concerns and crosscutting concerns. After implementing the common logic of cross-cutting concerns such as logging, transaction management, and permission control, developers can focus on core concerns and devote their energies to solving business logic. At the same time, the functionality provided by these encapsulated crosscutting concerns can be reused to the fullest part of the business logic, without the need for special coding by developers, or because of the ability to modify crosscutting concerns to affect specific business functions.

In order to build loosely coupled, scalable enterprise systems, the crosscutting techniques applied to AOP are usually divided into two types: dynamic crosscutting and Static crosscutting. 2.2.2 Dynamic crosscutting

Dynamic crosscutting is the process of creating behavior in one aspect through pointcuts and connection points, which can be applied horizontally to existing objects at execution time. Dynamic crosscutting is typically used to help add logging or authentication to various methods in the object hierarchy. In many application scenarios, the dynamic crosscutting technique basically represents AOP.

The core of dynamic crosscutting technology includes join Point (junction), Points cut (pointcut), advice (notification) and aspect (aspect). In the front, I have outlined the meaning of these terms separately. Next, I'll take a concrete example to further illustrate their implications for the implementation of AOP dynamic cross-cutting.

Consider an e-business system, need to add, delete and other management operations. There is no doubt that in a real-world scenario, these behaviors should be combined with rights management, and only authorized users can enforce them. Using the traditional design method, the pseudo code is as follows:

public class OrderManager
{
    private ArrayList m_orders;
    Public OrderManager ()
    {
       m_orders = new ArrayList ();
    }
    public void AddOrder (order)
    {
        if (permissions). Verify (permission.admin))
        {

            m_orders.add (order);
        }
    }

    public void Removeorder (order)
    {
        if (permissions). Verify (permission.admin))
        {
            m_orders.remove (order);
        }
    }
}

Similarly, in the e-business system, commodity management is also required, and it uses the same authorization mechanism:

public class Productmanager
{
    private ArrayList m_products;
    Public Productmanager ()
    {
        m_products = new ArrayList ();
    }
    public void Addproduct (product product)
    {
        if (permissions). Verify (permission.admin))
        {
             m_products.add (product);
        }
    }
    public void Removeproduct (product product)
    {
        if (permissions). Verify (permission.admin))
        {
             m_products.remove (product);
        }
    }
}

So, in the whole e-business system, the core business includes order management and commodity management, they all need the same rights management, as shown in Figure 2.4:


There is no doubt that using AOP technology, we can isolate the core concerns of the system and crosscutting concerns, from the horizontal point of view, intercepting the internal message of business management behavior in order to achieve the purpose of weaving permission management logic. When a method such as AddOrder () is executed, the system authenticates the user's permissions and invokes the crosscutting concern logic, so the method is the AOP join point. For an e-business system, each method that requires permission validation is a separate join point. Because permission validation is performed before each method executes, you only need to define a point cut for this series of join point. When the system executes to the join point, it looks for the corresponding point cut according to the definition, and then executes the logic that this crosscutting concern needs to be implemented, namely advice. Point cut and advice are combined into a privilege management aspect.


Since aspect is an encapsulated object, we can define such a aspect:

Private static aspect authorizationaspect{...}

Then define point cut in this aspect, and in point cut, define the method that needs to intercept the context message, for example:

Private Pointcut authorizationexecution ():
Execution (public void Ordermanager.addorder (order)) | |
Execution (public void Ordermanager.deleteorder) | |
Execution (public void productmanager.addproduct (Product)) | |
Execution (public void productmanager.deleteproduct (Product));

Because permission validation is done before the order management method executes, the permission check is defined in before advice:

Before (): Authorizationexecution ()
{
    if! ( Permissions. Verify (permission.admin))
    {
        throw new unauthorizedexception ();
    }
}

By defining such a complete aspect, when the system calls the associated method of OrderManager or Productmanager, it triggers the point cut and then invokes the corresponding advice logic. Since then, the OrderManager and Productmanager modules have completely lifted the dependency relationship with the Rights Management module, and eliminated the inevitable duplication code in the traditional design. This is advantageous for building a loosely coupled, scalable system software. 2.2.3 Static crosscutting

Static crosscutting differs from dynamic crosscutting in that it does not modify the execution behavior of a given object. Instead, it allows you to modify the structure of an object by introducing additional method fields and properties. In addition, static crosscutting can attach extensions and implementations to the basic structure of an object. In an AOP implementation, static crosscutting is often referred to as introduce or mixin.

Static crosscutting is a relatively small concern in AOP technology. In fact, the potential of this technology is enormous. With static crosscutting, architects and designers can effectively build models of complex systems using a truly object-oriented approach. Static crosscutting allows you to insert public behavior across the entire system without creating a deep hierarchy, in a way that is inherently more elegant and more realistic in structure. Especially when the application system is developed, the static crosscutting technology will play a great role if it is necessary to introduce the Third-party products and the API library without modifying the original code.

For example, a mail-receiving system has been implemented, with class mail completing the function of sending and receiving mail. However, after the product delivery, found that the system has a flaw, in the sending and receiving of mail, did not implement the verification function of the mail address. Now, the Third-party product already provides the authentication function interface ivalidatable:

Public interface ivalidatable
{
    bool validateaddress ();
}

We can use the adapter pattern in the design pattern to complete the call to the Third-party product API. We can define a new class Mailadapter, which implements the Ivalidatable interface and inherits the Mail class:

public class mailadapter:mail,ivalidatable
{public
     bool Validateaddress ()
     {
         if (this.gettoaddress) ( != null)
         {return
             true;
         }
         else
         {return
             false;
     }
}}

By introducing the Mailadapter class, the operation that the original mail object completes will be replaced by the Mailadapter object. However, while this implementation solves the problem of introducing a new interface, the code similar to the following is not compiled:

Mail mail = new mail ();
Ivalidatable validate = ((ivalidatable) mail). Validateaddress ();

The first line of code must be modified as follows:

Mail mail = new Mailadapter ();

With the static crosscutting technology of AOP, the Ivalidatable interface can be woven into the original mail class, which is a very image introduce function, and its implementation is still done in aspect:

Import com.acme.validate.Validatable;

Public aspect Mailvalidateaspect
{
    declare parents:mail implements ivalidatable;

    public boolean mail.validateaddress ()
    {
         if (this.gettoaddress ()!= null)
         {return
              true;
         }
         else
         {return
              false;
    }
}}

The static crosscutting approach does not introduce new classes like Mailadapter, but rather by defining the mailvalidateaspect aspect, using crosscutting techniques to introduce new methods for mail Classes validateaddress (), This enables the extension of mail. So the following code is entirely feasible.

Mail mail = new mail ();
Ivalidatable validate = ((ivalidatable) mail). Validateaddress ();
3 Advantages of AOP technology

The advantages of AOP technology are obvious. In the object-oriented world, a variety of methods and design principles are proposed to ensure the reusability and scalability of the system, in order to build a loosely coupled, easily extensible software system. For example, the "design pattern" proposed by GOF provides us with a model and guideline for design. Design patterns take advantage of object-oriented features such as inheritance, polymorphism, separation of responsibilities, inversion of dependencies, abstraction-oriented, interface-oriented, and ultimately the design of flexible, scalable, reusable class libraries, components, and the architecture of the entire system. In the process of design, the behavior of object, the interface of exposure, the relationship among objects and the appearance of objects in different levels are embodied through various patterns. However, in view of the particularity of object encapsulation, the tentacles of "design pattern" always have a big fuss in interface and abstraction, but there is nothing to do inside the object.

With "crosscutting" technology, AOP technology can go deep into the inside of the object and the message passed between the interception methods is used by me. The complete isolation of core concerns from crosscutting concerns allows us to program "aspect" independently. It allows developers to dynamically modify the static OO model and construct a system that grows to meet new requirements, just as real-world objects change themselves throughout their lifecycle, and applications can have new features in development.

The advantage of applying AOP technology when designing software systems is:

(i) When defining all the requirements of an application for a service, such as a log. By identifying the focus, the service can be better defined, better coded, and more functional. This approach also addresses the problems that arise when code involves multiple functions, such as changing a feature that might affect other functions, and in AOP it is called "Tangle (tangling)".

(ii) The analysis of discrete aspects using AOP techniques will help to designate a development team expert who specializes in the work. The best person in charge of this work will be able to use their relevant skills and experience effectively.

(iii) sustainability. In standard object-oriented project development, different developers often write the same code for a service, such as logging. They then process the logs separately in their implementation to meet the needs of different individual objects. By creating a separate piece of code, AOP provides a durable, simple solution to this problem that emphasizes the reusability and maintainability of future functionality: there is no need to rewrite the log code over and over throughout the application, AOP makes it possible to write only the log aspect (logging aspect) is possible and can be used to provide new functionality for the entire application.

All in all, the advantages of AOP technology have greatly reduced the amount of code that needs to be written, saving time and controlling development costs. It also enables developers to focus on the core business logic of the system. In addition, it facilitates the creation of loosely coupled, reusable and scalable large software systems.


turn from : http://wayfarer.cnblogs.com/articles/241024.html

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.