Spring (v) AOP

Source: Internet
Author: User


AOP Overview

AOP is the abbreviation of Aspect oriented programming, which means: face-cutting programming, through the pre-compilation method and run-time dynamic agent implementation of the unified maintenance of the program functions of a technology. AOP is a continuation of OOP, a hotspot in software development, an important content in the spring framework, and a derivative model of functional programming. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.

A technology that can dynamically and uniformly add functionality to a program without modifying source code is possible through precompilation and run-time dynamic proxies. AOP is actually a continuation of the GOF design pattern, and the design pattern pursues the decoupling between the caller and the callee, improving the flexibility and extensibility of the code, and AOP can be said to be an implementation of this goal.

Extensive support for aspect-oriented programming is provided in spring, allowing for the development of cohesion through the separation of application business logic with system-level services such as auditing (auditing) and transaction (transaction) management. The Application object only implements what they should do-complete the business logic-that's all. They are not responsible (or even conscious) for other system-level concerns, such as log or transaction support.

AOP is primarily designed to be able to separate code from business logic code, such as logging, performance statistics, security control, transaction processing, exception handling, and so on, by separating these behaviors, and we want to be able to isolate them to non-instructional methods of business logic, and then change those behaviors without affecting the code of the business logic.

AOP and OOP

AOP and OOP complement each other, object-oriented programming breaks down programs into objects of all levels, while aspect-oriented programming decomposes the program's running process into facets. Can be simply understood as: object-oriented programming from the static perspective of the program structure, while the aspect-oriented programming is from the dynamic perspective of the program running process.

OOP (Object-oriented programming) encapsulates the entity and its attributes and behaviors of the business process in an abstract way for clearer and more efficient logical unit partitioning.
AOP is the extraction of facets in the process of business processing, which is faced with a step or stage in the process of processing, in order to obtain the isolation effect of low coupling between parts of the logic process. These two kinds of design thought have the essential difference in the goal.

For example, encapsulating a business entity like "employee" is naturally a oop/ood task, and we can create an "employee" class for it and encapsulate the attributes and behaviors associated with "employee". However, it is impossible to encapsulate "employee" with the idea of AOP design. Similarly, the segmentation of the action fragment for permission checking is the target area of AOP. It is a bit nondescript to encapsulate an action by Ood/oop. It can be considered that ood/oop is oriented to the field of nouns, AOP oriented verb field.

In traditional OOP programming, the object is the core, and the entire software system consists of a series of interdependent objects that are abstracted into classes and that allow class inheritance to manage the general to special relationship between classes and classes. Because classes can inherit, properties that have the same functionality or attributes can be abstracted into a hierarchical class architecture. The idea of OOP is very powerful in itself, and its advantages are obvious to the industry. But as the scale of the software increases and the application is constantly upgraded, OOP is not good at dealing with the needs of certain scenarios.

For example, as more and more non-business requirements (logs and validations, etc.) are added, the original business method expands dramatically. Each approach has to deal with the core logic while still having to take into account several other concerns, which can lead to code clutter. In terms of log requirements, in order to meet this single requirement, we have to repeat the same log code many times in multiple modules (methods). If the log requirements change, all modules must be modified, which can lead to code fragmentation and is not conducive to maintenance.

In response to some of these problems, many people will think that a well-defined OOP should also be solved. The interface of well-defined OOP can really solve some of these problems. However, for an interface in OOP, it still requires us to invoke the relevant method in the corresponding module, which is unavoidable by OOP, and everything becomes a mess once the interface has to be modified. AOP is not the case, you just need to modify the corresponding Aspect, and then re-weave (weave). But AOP is no substitute for OOP. The core requirements will still be implemented by OOP, and AOP will be integrated with OOP for a complementary length.


Embark on a journey of AOP



When you apply AOP programming, you still need to define public functionality, but you can clearly define where and how this function is applied, without having to modify the affected classes. This way the crosscutting concerns are modularized into special objects (facets).
Benefits of AOP:
There is good isolation between the steps, each logic is in one place, the code is not scattered, easy to maintain and upgrade.
Source-code independence. The business module is more concise and contains only the core business code.

AOP Terminology

>Facets (Aspect):A special object that is modularized by crosscutting concerns (functions that span multiple modules of the application). Facets are used to organize multiple advice,advice that are defined in facets.

>Enhanced Processing (Advice):An AOP framework performs enhanced processing at a particular pointcut. Processing has "around", "before" and "after" and other types.

>goal (target): Objects that are enhanced by the AOP framework are also known as enhanced objects. If the AOP framework is implemented by a dynamic AOP implementation, the object is an object that is proxied.

>agent (proxy): The object created by the AOP framework can simply be understood as the enhancement of the target object by the proxy. Spring's AOP proxy can be either a JDK dynamic agent or a cglib proxy. The former is the proxy for the target object that implements the interface, and the latter is the target object agent that does not implement the interface.

>connection point (Joinpoint): A specific location for a program execution, such as before a method call to a class, after a call, after a method throws an exception, and so on. The connection point is determined by two information: The program execution point represented by the method, and the orientation represented by the relative point. For example, the connection point before the Arithmethiccalculator#add () method executes, the execution point is Arithmethiccalculator#add (), and the position is before the method executes.

>Tangent Point (pointcut): You can insert a connection point for enhanced processing. When a connection point meets the specified requirements. The connection point adds enhanced processing, which becomes the pointcut. Each class has multiple connection points: for example, all the methods of Arithmethiccalculator are actually connection points, that is, the connection point is an objective transaction in the program class. AOP navigates to a specific connection point through a pointcut. Analogy: A connection point is equivalent to a record in a database, and a tangent is equivalent to a query condition. Tangency and connection points are not a one-to-one relationship, a pointcut matches multiple connection points, and the pointcut is described by the Org.springframework.aop.Pointcut interface, which uses classes and methods as query criteria for connection points.

>Introduction (Introduction): Used to declare additional methods or properties (also known as connection type declarations (Inter-type Declaration)) for a type. Spring allows the introduction of new interfaces (and a corresponding implementation) to any Proxied object. For example, you can use ingestion to enable a bean to implement the IsModified interface to simplify the caching mechanism.

>weave in (Weaving): Connects slices to other application types or objects, and creates an object to be notified. These can be done at compile time (for example, with the AspectJ compiler), at class load time, and at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time.

Notification Type

> Pre-notification (before advice): A notification that is executed before a connection point, but this notification does not block the execution process before the connection point (unless it throws an exception).

> post Notification (after returning advice): A notification that is executed after a connection point is completed normally: for example, a method does not throw any exceptions and returns normally.

> Exception Notification (after throwing advice): A notification that is executed when a method throws an exception exits.

> Final notification (after (finally) advice): A notification that is executed when a connection point exits (whether it is a normal return or an unexpected exit).

> Surround notification (Around Advice): A notification that surrounds a connection point, such as a method call. This is the most powerful type of notification. Surround notifications can accomplish custom behavior before and after a method call. It also chooses whether to continue execution of the connection point or to return its own return value directly or throw an exception to end the execution.

Surround notifications are the most common types of notifications. Like ASPECTJ, Spring provides all types of notifications, and we recommend that you use the simplest possible notification type to achieve the functionality you need. For example, if you just need a return value for a method to update the cache, it's best to use a post-notification instead of a surround notification, although wrapping the notification can do the same thing. Using the most appropriate notification type can make the programming model simple and avoid many potential errors. For example, you do not need to invoke the proceed () method for wrapping notifications on Joinpoint, there is no problem with the call.

implementing AOP using AspectJ

ASPECTJ is a Java-based AOP framework that provides powerful AOP capabilities. Spring4.0 's AOP is well integrated with ASPECTJ.

AspectJ mainly consists of two parts: one defines how to express and define the syntax specification in AOP programming, and the other part is the tool part, including compiler, debugging tool, etc.

> Local Installation aspectj

ASPECTJ is an open source project under Eclipse: http://www.eclipse.org/aspectj/ downloads.php, after the download is complete, get a Aspectj-1.8.9.jar file, open the Command Line window, enter the path of the Aspectj-1.8.9.jar file, enter the following command:

Java-jar Aspectj-1.8.9.jar


Running the command above will jump out of the following window, follow the prompts to select the installation path, and then add classpath, Path, respectively, as prompted.





After successfully installing ASPECTJ, you will see the following file structure under the D:\developer\java\aspectj1.8 path (ASPECTJ installation path). The



>bin The path to the AJ, Aj5, AJC, Ajdoc, ajbrowser commands, where the AJC command is a common command and acts like 9javac, which is used to compile-time enhancements to ordinary Java classes. The

>doc path contains ASPECTJ instructions, reference manuals, API documentation, and more. The 4 jar package files under the

>lib path are the core class libraries of the ASPECTJ.

> Install aspectj in Eclipse

To create a project using ASPECTJ in Eclipse, configure the ASPECTJ plug-in AJDT. First, open the AJDT download page: http://www.eclipse.org/ajdt/downloads/, see the following page.



Locate the AJDT update address for the Eclipse version and copy it to the Eclipse plugin installation URL search box.



Click "Next" to install, restart Eclipse after installation, click "New" New project, you can see the aspect project related options in the New dialog box.



This allows you to create a ASPECTJ project application in Eclipse.

>ASPECTJ Application Example

Write two simple Java classes to simulate the business logic components in the system, and the actual application is the same regardless of the number of classes, the ASPECTJ is handled the same way.

package com.afy.app.service;publicclass Hello{    // 定义一个简单方法,模拟应用中的业务逻辑方法    publicvoidfoo()    {        System.out.println("执行Hello组件的foo()方法");    }    // 定义一个addUser()方法,模拟应用中的添加用户的方法    publicintaddUser(String name , String pass)    {        System.out.println("执行Hello组件的addUser添加用户:" + name);        return20;    }}

Another World component class is as follows.

package com.afy.app.service;publicclass World{    // 定义一个简单方法,模拟应用中的业务逻辑方法    publicvoidbar(){        System.out.println("执行World组件的bar()方法");    }}


The two business component classes here define three methods for simulating the three business logic methods that the system contains, using a main program to simulate three business methods that the system calls two business components.

Packagecom. Afy. Test;Importcom. Afy. App. Service. Hello;Importcom. Afy. App. Service. World;public class aspectjtest{public static void Main (string[] args) {Hello hello = new Hello ();Hello. Foo();Hello. AddUser("Monkey King","7788");World World = New World ();World. Bar();}}


After running the program output is as follows.



Now suppose that the customer requires a permission check before all business methods are executed, and if the traditional programming method is used, the developer must first define a method of permission checking, then open each business logic method, modify the source code of the business method, and increase the method of invoking the permission check. But this approach needs to be modified for every business method in all business components, so it is not only easy to introduce new errors, but also to maintain the costs considerably. If you are using ASPECTJ's AOP support, simply add the following special "Java class".

package com  .afy  .app    Public aspect Authaspect {//Specifies Org.crazyit  .app  .service  any of the classes in the package, execute the following code block before any method///The first asterisk indicates that the return value is unlimited; the second asterisk indicates that the class name is not limited;//The third asterisk represents the square Dharma name not limited to; in parentheses: Represents any number and type of parameter before (): Execution (* com  .afy
       .app  .service . *. * (..)) {System.out  .println  ( "impersonation for permission check ..." ) ;  }}


To run the program, you can see that something magical has happened.



The above code does not use class, interface, Enum, and so on, and using Aspect,aspect is not a Java supported keyword, is ASPECTJ to recognize the keyword, Authaspect is not a Java class, and the code body is not a method, but instead specifies that the code in the code block is called automatically by AspectJ before certain methods of some classes are executed.

from the running results, it is not necessary to modify the business components, such as Hello.java, World.java, but to meet the customer's needs. If the customer proposes new requirements again, such as the ability to add logging after all business methods have been executed. Here we define a logaspect, the program is as follows.

package com  .afy  .app    Public aspect Logaspect {//defines a pointcut, which is named Logpointcut//The pointcut represents the pointcut expression given later, so that the pointcut expression can be taken pointcut LOGPOINTC UT (): Execution (* com  .afy  .app  .service . *. * * (..))     After (): Logpointcut () {system.out   ( "Analog logging ..." ) ; }}  


Run the program and the result will be jiangzi.



You can do it! A pointcut:logpointcut () is defined in the program, which is used to name a subsequent pointcut expression, which facilitates reuse of the pointcut expression, if there is more than one code block in the program that needs to use the pointcut expression. These codes can be used to directly reuse custom logpointcut without having to write tedious pointcut expressions repeatedly.

If you now need to start a transaction before all business methods for the business component and close the transaction at the end of the method execution, simply add the Txaspect.java code.

Packagecom. Afy. App. Aspect;import org. AspectJ. Lang. Proceedingjoinpoint;Public aspect Txaspect {//Specify Execute Hello. SayHello() method when you execute the following code block, Object around ():Pager(*com. Afy. App. Service.*.*(..)) {System. out. println("Simulate open transactions ...");Callback original Target Method Object rvt = Proceed ();System. out. println("Simulate end transaction ...");Return RVT;}}

See how our program works.



Very powerful Oh, there is no! The code specifies that proceed () represents a callback to the original target method, so that code before proceed () is added to the target method, and the code after the proceed () code is added after the target method.

Spring (v) 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.