Spring Study Notes (3) AOP getting started

Source: Internet
Author: User

Insert a system service (such as Logging and Security) unrelated to the business logic in a service process. This logic is called Cross-cutting concerns, the Cross-cutting concerns is designed as an object. This special object is called Aspect ), aspect-oriented programming focuses on Aspect design and Weave ).

AOP and OOP do not conflict with each other. They are two complementary design models. Spring AOP is a technology for Implementing AOP.

I. Introduction to AOP

1.1 exploring the proxy mechanism of AOP

This example contains the Logging action.

Public class HelloSpeaker {

Private Logger logger = Logger. getLogger (this. getClass (). getName ());

Public void hello (String name ){

Logger. log (Level1.INFO, "hello method start ...");

System. out. println ("hello" + name );

Logger. log (Level1.INFO, "hello method end ...");

}

}

In this example, the single responsibility principle is violated. For HelloSpeaker, logging does not belong to its business logic, but the logging code is in the Cross-cutting HelloSpeaker class.

Such code is everywhere, making the system difficult to maintain. If the required Service is not only a log, such as permission detection and transaction management, the system maintenance burden will be increased. It even obfuscated its responsibilities.

You can use the Proxy mechanism to solve this problem: static Proxy and dynamic Proxy.

L static proxy

In static proxy, the proxy object and the proxy object must implement the same interface. The system functions such as Logging can be implemented in the proxy object and called by the proxy object as needed. Therefore, the proxy object can only retain the responsibilities related to the business logic.

For example:

Public Interface IHello {

Public void hello (String name );

}

HelloSpeaker of business logic implements this interface.

Public class HelloSpeaker {

Public void hello (String name ){

System. out. println ("Hello" + name );

}

}

This class does not insert content unrelated to the business logic.

The implementation of Log service will be placed in the proxy object, and the proxy object must implement the IHello interface. For example:

Public class HelloProxy implements IHello {

 

Private Logger logger = Logger. getLogger (this. getClass (). getName ());

Ihello helloobject;

Public helloproxy (ihello helloobject ){

This. helloobject = helloobject;

}

 

Public void Hello (string name ){

Log ("Hello method start ...");

This. helloobject. Hello (name );

Log ("Hello method end ...");

}

 

Public void log (string MSG ){

Logger. Log (MSG );

}

}

Compile the test client program.

Public class proxytest {

Public static void main (string [] ARGs ){

Ihello proxy = new helloproxy (New hellospeaker ());

Proxy. Hello ("sh ");

}

}

A static proxy interface serves only one type of objects. When the program is a little large, it cannot be competent.

L Dynamic proxy

You do not need to write specific proxy objects for specific objects and methods. Dynamic proxy allows a processor to serve multiple objects. First, a handler must implement the java. lang. reflect. InvocationHandler interface, for example:

Public class LogHandler implements InvocationHandler {

Private Logger logger = Logger. getLogger (this. getClass (). getName ());

Private Object delegate;

 

Public Object bind (Object delegate ){

This. delegate = delegate;

Return Proxy. newProxyInstance (

Delegate. getClass (). getClassLoader (),

Delegate. getClass (). getInterfaces (),

This );

}

Public Object invoke (Object proxy, Method method, Object [] args)

Throws Throwable {

Object result = null;

Try {

Log ("method starts .." + method );

Result = method. invoke (delegate, args );

Logger. log ("method ends" + method );

}

Catch (Exception e ){

Log (e. toString ());

}

Return result;

}

 

Private void log (String message ){

Logger. log (message );

}

}

The main concept is to use the Proxy. newProxyInstance () static method to create a Proxy. When creating a Proxy, you must inform the interface you want to Proxy, and then you can operate on the created Proxy object. In each operation, the InvocationHandler's invoke () method will be executed, and the method name and execution parameters of the proxy object will be passed in. In fact, the method to be executed will be handed over to method. invoke (), method. the object returned by invoke () is the return result after the actual method is executed.

To execute a dynamic proxy, you must also implement the proxy interface. Same as static proxy. For example:

Public Interface IHello {

Public void hello (String name );

}

Enable the class of business logic to implement the IHello interface, for example:

Public class HelloSpeaker implements IHello {

Public void hello (String name ){

System. out. println ("Hello" + name );

}

}

Write a customer program:

Public class ProxyTest {

Public static void main (String [] args ){

LogHandler logHandler = new LogHandler ();

 

IHello helloProxy = logHandler. bind (new HelloSpeaker ());

HelloProxy. hello ("SH ");

}

}

Differences from static Proxy:

LogHandler no longer serves specific objects and interfaces.

Relationship between proxy and AOP:

Use a proxy to extract logs and other actions or tasks unrelated to the business logic and design them into a service object, such as HelloProxy and LogHandler mentioned earlier. Such an object is called a plane (Aapect ).

The Aspect in AOP refers to actions or services such as logs, which convert these actions (Cross-cutting concerns) it is designed as a general Aspect object with clear responsibilities that do not involve specific business logic objects. This is Aspect-oriented programming and AOP.

1.2 concepts and terminology of AOP

The full name of AOP is Aspect-Oriented Programming. Many terms about AOP are too abstract and it is not easy to understand the meaning of the term, here we will compare the previous examples of proxy mechanisms to introduce the terminology and concepts of AOP:

  • Cross-cutting concern

In the example of the dynamicproxydemo project, the recorded action was originally taken into the business process of hellospeaker itself, and similar to recording the action, for example, security checks, transactions, and other system-level services are often seen in some applications as the processing process of each object, these actions are called cross-cutting concerns in AOP terminology.
 

The meaning of cross-cutting concerns can be strongly recalled as illustrated in the following figure. For example, the original business process is simple:

To add logging and security check services, if the program code of an object is hard to write related logging and Security Program fragments, the concepts of cross-cutting and cross-cutting concerns can be interpreted as follows:

 

If cross-cutting concerns is directly written in a stream of objects in charge of a business, it will increase the cost of the maintenance program. For example, if you want to modify or remove the record function from the object today, you must modify all program codes that have written services and recompile them. On the other hand, cross-cutting concerns is mixed in the business logic, this makes the logic or program Writing of the business object more complex.

  • Aspect

Collects Cross-cutting concerns scattered among various business objects and designs independent reusable objects called Aspect, for example, in the DynamicProxyDemo project, the login action is designed as a LogHandler category. The term of the LogHandler category in AOP is a specific example of Aspect, which focuses on Aspect recognition in AOP, separate the service from the business process. When you need the service, stitch it to the application. When you do not need the service, you can immediately remove it from the application, reusable components in applications do not need to be modified. For example, HelloSpeaker in the DynamicProxyDemo project represents a role that can be reused in applications, when it needs to record the service, it does not need to modify its own program code.

On the other hand, for reusable components in an application, in the design of AOP, it does not need to know the existence of objects that process services. Specifically, service-related APIs do not appear in reusable application components, which improves the reusability of these components. You can apply these components to other applications, instead of coupling with the current application framework because some services are currently added.

  • Advice

The specific implementation of Aspect is called Advice. In terms of recorded actions, Advice includes how the real recorded program code is implemented, for example, the LogHandler category in the DynamicProxyDemo Project is a specific instance of Advice. Advice includes the behavior of Cross-cutting concerns or the service to be provided.

  • Joinpoint

The point or time when Aspect adds a business flow to the application execution is called Joinpoint. Specifically, it is the time when Advice is called for execution in the application, this time may be before or after a method is called (or both), or when an exception occurs.

  • Pointcut

Pointcut is a definition. With this definition, you can specify the Joinpoint in which an Aspect is applied to the application. Specifically, you can write Pointcut in a definition file to illustrate which Aspect is to be applied to which Joinpoint in the application.

  • Target

An Advice application object or Target object. For example, HelloSpeaker in the DynamicProxyDemo project is the Target of the Advice LogHandler.

  • Introduction

For an existing category, Introduction can add actions for it without modifying programs of this category. Specifically, you can add a written and compiled category, add some methods or actions dynamically during execution without modifying or adding any line of program code.

  • Proxy

In the book "Expert One-on-One J2EE Development WIthout EJB", Rod Johnson and Juergen Hoeller mentioned in chapter 8 that the implementation of AOP has five main policies: dynamic Proxies, Dynamic Byte Code Generation, Java Code Generation, Use of a Custon Class Loader, Language Extensions.

In the previous static proxy and dynamic proxy, the actual program example has been used to introduce the implementation of the proxy mechanism. Spring AOP is mainly implemented through dynamic proxy.

  • Weave

The process of applying Advice to objects is called Weave. In AOP, the stitching method has several time points: Compile time and Classload time), execution period (Runtime ).
 

In combination with the DynamicProxyDemo example, we use images of the AOP-related terms described above to express them. This helps you understand and understand each term:

 

1.3 Spring AOP

Different AOP frameworks have different implementation methods for the AOP concept. The main difference is the richness of the provided Joinpoints and Aspects, and how they are stitched (Weave) to the application (such as the Pointcuts definition method ).

Spring's Advices is written in the Java programming language without using a specific AOP language. When defining Pointcuts, you can use XML configuration files, both of them are familiar to Java developers. You don't have to learn specific syntax, so you can use Spring AOP in the familiar Java programming language and XML format.

Spring's AOP implementation implements the interface defined by the AOP Alliance (http://www.sourceforge.net/projects/aopalliance), which is a Joint plan (Joint project) composed of many groups ), the implementation requirements of these groups for AOP must comply with the developed interface specifications to standardize the Java AOP implementation interface, to increase the portability of AOP implementation classes between different Java applications.

Spring's Advices are imported to Targets during execution. You can make Targets implement a pre-defined interface, then Spring will use java during execution. lang. reflect. proxy for dynamic Proxy. If the interface is not implemented, Spring will use CGLIB to generate a sub-category for your Targets as Proxy category (Proxy classes ).

In Spring AOP, you should give priority to implementing interfaces, which can reduce the coupling between application components and use Proxy classes, because sub-categories must be generated, proxy cannot be performed for methods declared as final, and this method is basically to make some Third parties unable to change the original code (third‐party) type or Legacy category (Legacy classes.

Spring only supports the Joinpoints of the method, that is, Advices will be applied before and after the method call. Spring does not support the Jointpoints of Field members, because in Spring's design philosophy, supporting the Joinpoints of Field members will damage the encapsulation of parts.

Spring provides three methods to implement AOP.

1. The traditional method for implementing Spring APIs.

2. XML-based settings.

3. Use Annotation support of @ AspectJ.

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.