Learn AspectJ (2)
This article continues the previous content, will introduce aspectj applications and some basic languages of AspectJ.
Aspectj application range
As mentioned earlier, AspectJ can be used for different stages of application development. The specific application of AspectJ in different stages will be discussed below.
Developments (developments)
Developments can be easily removed from real products. The product is available for development processes and production processes, but only affects a few classes.
This section will use several examples of how to use how the development phase of Java applications is used. These aspects include debugging, testing and performance testing. Aspects defined behaviors include simple code tracking, internal contacts of test applications, and more. Using Aspectj not only makes modular these functions, but also makes it possible to turn and close these functions as needed.
Code Tracking (Tracing)
Let us first take a look at how to add visibility within a program. We define a simple aspect for code tracking and output some information when each method is called. In the previous graphic editing example, such aspects may only draw a point for a simple track.
askIMPLETRACING {
Pointcut tracedcall ():
Call (Void FigureElement.draw (GraphicsContext));
Before (): tracedcall () {
System.out.println ("Entering:" thisjoinpoint;
}
}
The code uses thisjoinPoint variable. In all notices, this variable will be bound to objects describing the current connection point. So the above code outputs the following information when accepted the DRAW method each time a figureElement object:
Entering: Call (Void FigureElement.draw (graphicsContext))
Usually we place several output statements in a specific place, while you need to find them to delete them at the end of the debugging, do not only make our code, but also time. And use aspectj we can overcome two questions, we can capture any code segments you want to observe by defining cleaning points, using notifications can write output statements within aspect without modifying source code, when not required to track statements It is also easy to delete and recompile the code from the application very easy.
Pre-and post-conditions
Many programmers use the Design by Contract. This form of programming requires explicit prerequisites to ensure that the method is appropriate, and the explicit subsequent condition test guarantee method is working properly. Aspectj makes it possible to modularize these two conditional tests. For example, the following code
Aspect pointsboundschecking {
PointCut SetX (INT X):
(Call (vid figureelement.setxy (int, int)) && args (x, *))
|| (Call (Void Point.Setx (IN)) && args (x));
PointCut SetY:
(Call (void figureelement.setxy (int, int) && args (*, y))
|| (Call (Void Point.Sety (int)) && args (y);
Before (int x): setX (x) {
IF (x
Throw New IllegaArgumentException ("x is out of bounds.");
}
Before (int y): sety (y) {
IF (Y
}
}
It implements the boundary detection function. When the FigureEleMent object moves, if the value of the X or Y exceeds the defined boundary, the program will throw an ILLEGALARGUMENTEXCEPTION exception.
Contract enforcement
The attribute-based cross-cutting mechanism is very useful in defining a more complex contract implementation. A very powerful feature is that it can force a specific method call to only appear in the corresponding program, and do not appear in other programs. For example, the following aspects have been implemented, making it only in a well-known factory method to register and add a FigureEleMent object. The purpose of implementing this limit is to ensure that no one of the first figureElement objects are registered multiple times.
STATIC aspect registrationprotecion {
Pointcut register (): call (void registry.register (figureelement));
Pointcut canregister (): withincode (static * framelelement.make * (.));
BEFORE (): register () &&! canregister () {
Throw New IllegaCCESSEXCEPTION ("Illegal Call" thisjoinPoint;
}
}
This aspect uses the useincode initial clearance point, which represents all connection points that appear in the factory method of the FigureElement object (with Make start). Declaring an exception in the Before notification, which is used to capture any call to the Register method that is not generated within the factory method code. This notification throws a runtime abnormality at a particular connection point, but aspectj can be better. Using Declare Error, we can declare a compile time error.
STATIC aspect registrationprotecion {
Pointcut register (): call (void registry.register (figureelement));
Pointcut canregister (): withincode (static * framelelement.make * (.));
Declare error: register () &&! canregister (): "Illegal Call"
}
When using this aspect, if there are defined these illegal calls in the code we will not be compiled. This situation only occurs when we only need static information, if we need dynamic information, when the prerequisites mentioned above are implemented, it can be implemented using an exception to throw a parameter in the notification.
Configuration Management (Configuration Management) (CONFIGURATION Management)
AspectJ's configuration management can be processed using techniques similar to Make-File. Programmers can compile their own aspects they want. Developers who do not want any aspects appear in the product phase can also compile the entire app by configuring their make-file using the traditional Java compiler.
Product schedule (Production aspects)
Aspects of this part will be described with reference to the application of production phase. Product aspects will add functions to the application, not just internal work of the program, not only to increase visibility within the internal work.
Change Monitoring
In the first example, the role is used to maintain a bit data sign, which illustrates whether the object is moved from the last display refresh start. In terms of implementation, such a function is very straightforward, the TestandClear method is displayed to be invoked to find a graphical element to move recently. This method returns the status of the flag and set it to false. Clearing point MOVE captures all methods that can be graphical movement. The AFTER notifies the intercepting the MOVE cleaner and sets the flag. Aspect movetracking {
Private static boolean dirty = false;
Public static boolean testandclear () {
Boolean Result = DIRTY;
Dirty = false;
Return Result;
}
PointCut Move ():
Call (void figureelement.setxy (int, int)) ||
Call (Void Line.Setp1 (Point) ||
Call (Void Line.Setp2 (POINT) ||
Call (void point.setx (int)) ||
Call (Void Point.Sety (int));
AfTer () returning: move () {
DIRTY = TRUE;
}
}
This simple example also illustrates some benefits of using Aspectj in the product code. Consider using a normal Java code to implement this feature: It is possible to include auxiliary class including the flag, TestandClear, and SetFlag methods. These methods require each moving graphic element to contain a call to the setflag method. The call to these methods is a cross-cutting point in this example.
· The display of the display of the crossed point
· Function is easy to plug
· Realize more stable
Transcending context
The context of cross-cutting structure is a very complex part of the Java program. Consider implementing a feature that allows the customer to set the color of the graphic object created. This requirement needs to pass from the client to a color or color plant. To add a parameter in a large number of methods, it is only familiar with all programmers to deliver the context information.
Using aspectj, this context-delivered manner can be implemented in a modular manner. The AFTER notification in the following code is only running when a factory method of a graphic object is called in a method control process of the customer ColorControllingClient.
Aspect colorControl {
Pointcut CcClientCflow (ColorControllingClient Client):
Cflow (Call (* * (.)) && target (client));
Pointcut make (): call (figureelement first frame.make * (..));
After (ColorControllingClient C) Returning (FigureElement Fe):
Make () && ccclientcflow (c) {
Fe.SetColor (C.Colorfor (Fe));
}
}
This aspect only affects a small part of the method, but pay attention to the non-AOP implementation of this function may need to edit more methods.
Provide a consistent behavior (providing consistent behavior)
The next example illustrates how attribute-based aspects provide consistent processing functions in many operations. This aspect is ensured that all public method records of the package com.bigboxco are thrown by any errors thrown. Public method call in the PUBLICMETHODCALL Captive Pack, After notification runs out after any such call throws an error and records this error.
ask PUBLICERROLGGING {
LOG log = new log ();
Pointcut publicMethodCall ():
Call (public * com.bigboxco. *. * (..)); after () throwing (Error E): PublicmethodCall () {
Log.Write (e);
}
}
In some cases, this aspect can be recorded twice. This occurs when the code inside the com.bigboxco package calls yourself in this package. To solve this problem, we can use the cflow initial clearance to exclude these internal calls:
After () throwing (Error E): PublicmethodCall () &&! cflow ()) {
Log.Write (e);
}
in conclusion
Aspectj is a simple and actual directional extension of Java language. AspectJ provides strong support for modularity of various cross-cutting points by joining several new structures. To join Aspectj to the Java development project is a direct and gradual task. A path is to use development reusable aspects by starting from the use of development to the product. Of course, other development paths can be selected. For example, some developers will be beneficial from the use of products, and the other people may immediately write reusable aspects.
AspectJ can use both name and attribute-based crossout points. Use only a few classes based on name cross-cut points, although they are small, they can reduce a lot of complexity than ordinary Java implementations. There is a small range or a wide range of aspects based on attribute crossout points. Using Aspectj, it has led to clean and modular implementation of cross-cutting points. When writing AspectJ, the structure of the crosstalk is very obvious and easy to understand. Aspects are also highly modular, making the development of the pluggable cross-cutting function becomes reality.
AspectJ provides a short introduction than these two parts. This series of next chapter, the Aspectj Language will introduce more details and features of the AspectJ language. Chapter 3 of Series, Examples will explain how to use aspectj through some complete examples. It is recommended that everyone carefully read the next two chapters and decides whether to join Aspectj in the project.
More information
1. Aspectj Installation and Configuration Guide
2. Learn Aspectj with me (1)
If you need to pay, please write a name author and source.