Annotation-based AOP of Spring basics

Source: Internet
Author: User
Tags aop

Background concept:

1) crosscutting concerns: Features scattered across multiple applications are called crosscutting concerns.

2) Notice (Advice): The work done on the slice. The notification is about what the slice is and when it is called.

Notifications that can be applied in 5:

Pre-notification (before): invokes the notification function before the target method is invoked.

Post notification (after): A notification is called after the target method completes, and no relationship method outputs anything at this time.

return notification (after-returning): Call notification when the target method executes successfully.

Exception Notification (after-throwing): A notification is invoked after the target method throws an exception.

Surround Notification (Around): Notifies the method that the notification has been wrapped, before and after the method call that is notified to execute the custom method.

3) connection point: The time to invoke a notification is called a connection point.

4) Tangent point (Pointcut): Notifies the range of connection points to be woven into.

5) Facets (Aspect): facets: A combination of notifications and pointcuts.

6) Introduction (Introduction): Allows us to add a new method or property to an existing class.

7) Weaving (weaving): the process of applying facets to a target object and creating a new proxy object.

Facets are woven into the target object at the specified connection point, and multiple points can be woven into the target object's life cycle:

Compile time: Facets are woven into the target class when it is compiled. This approach requires a special compiler. AspectJ's weaving compiler is the way in which the facets are woven in this manner.

Class load period: Facets are woven when the target class is loaded into the JVM. This approach requires a special classloader that can add bytecode to the target class before the target class is introduced into the application. The AspectJ5 is woven into the loading time and is supported in this way.

Run time: Facets are woven at some point in the application's run. In general, when facets are woven, the AOP container dynamically creates proxy objects for the target object, which is how the SPRINGAOP is woven into.

Note: Annotations are interpreted: the annotations themselves are not functional, just like XML, annotations and XML are metadata, metadata is the data that interprets the data, here is the so-called configuration.

The function of annotations comes from this place with annotations

Spring's support for AOP

SPRINGAOP The purpose of existence: decoupling.

AOP allows a group of classes to share the same behavior. Avoid adding functionality to classes by inheriting such high-coupling methods.

Spring supports 4 types of AOP support:

1) Agent-based classic SPRINGAOP;

2) pure Pojo plane;

3) @AspectJ annotation-driven facets;

4) injected AspectJ facets (for each spring version).

Note: The first three are variants of the SPRINGAOP implementation, and SPRINGAOP is built on a dynamic proxy, so spring's support for AOP is limited to method interception.

If an AOP requirement exceeds a simple method invocation (such as a constructor or attribute interception), a fourth approach is required.

Spring notifications are written in Java

Spring's notifications are pojo implemented and can be implemented based on annotations and XML, which is relatively simple and convenient.

ASPECTJ is implemented as a Java extension, with the advantage that the unique AOP language allows for more granular control and richer AOP working sets, but with a high learning cost.

Spring notifies the object at run time

The spring runtime does not create a proxy object, so we do not need a special compiler to weave into the SPRINGAOP facets.

Spring supports only method-level connection points

If you need to use a connection point interception feature other than method interception, we can use aspect to complement the functionality of Spring AOP.

To select a connection point by using a pointcut

Note: Only the execution indicator is actually performing a match, and the other indicators are qualifying matches, and the most important indicator we use when writing the pointcut definition should be the execution indicator, on which the other indicators are used to limit the matching tangent points.

To write a pointcut:

Define a performance interface:

Package com.spring.learn.index;

publicInterface Performance { publicvoid perform ();}

We want the pointcut expression to be required when the performance method in the performance interface triggers our notification:

Execution (* com.spring.learn.index.Performance.perform (..))

If we just need a class under a COM package, you can use within () to limit the match:

Execution (* com.spring.learn.index.Performance.perform (..)) && within (com.*)

Use && to express relationships; representation or relationship;! Represents non.

Note Replace with and or not in XML (because the symbol has a special meaning in XML).

Select a bean in the tangent point

In addition to the above indicator, spring also introduces a bean () indicator, which uses the bean ID or bean name as a parameter to constrain the pointcut to match only specific beans.

Creating slices with annotations

The performance interface is already defined, which is the target object in the slice. Use ASPECJ annotations to define facets.

Defining Facets:

Use the Audience class: View the facets of the show:

@Aspect Public classAudience {//this is before the show .@Before ("Execution (* com.spring.learn.index.Performance.perform (..))")     Public voidSilencecellphones () {System.out.println ("Mute the audience's phone"); }    //before the show@Before ("Execution (* com.spring.learn.index.Performance.perform (..))")     Public voidtakeseats () {System.out.println ("The audience is seated."); }    //after the show@AfterReturning ("Execution (* com.spring.learn.index.Performance.perform (..))")     Public voidapplause () {System.out.println ("A round of applause"); }    //The show failed .@AfterThrowing ("Execution (* com.spring.learn.index.Performance.perform (..))")     Public voidDemandrefund () {System.out.println ("Request a refund"); }}

@Aspect annotations show that audience is not just a pojo, but a facet.

The methods in audience define when notifications are invoked using annotations. Five annotations are provided in ASPECTJ to define the notification:

Each annotation uses a pointcut expression as his value. But our pointcut expression is reused four times, we can actually write it only once and then use the reference to do the same thing.

@PointCut annotations Define a reusable tangent point within a @aspect-defined slice:

@Aspect Public classAudience {//defining a named tangent point@Pointcut ("Execution (* com.spring.learn.index.Performance.perform (..))")     Public voidmypointcut () {} @Before ("Mypointcut ()")     Public voidSilencecellphones () {System.out.println ("Mute the audience's phone"); } @Before ("Mypointcut ()")     Public voidtakeseats () {System.out.println ("The audience is seated."); } @AfterReturning ("Mypointcut ()")     Public voidapplause () {System.out.println ("A round of applause"); } @AfterThrowing ("Mypointcut ()")     Public voidDemandrefund () {System.out.println ("Ask for a new show."); }}

So far, audience is still just an ordinary Pojo class, and even if @aspect annotations are used, they will not be treated as slices, nor will they be created as proxies that convert them to slices.

Additional configuration classes are required and the automatic proxy feature is started using Enableaspectj-autoproxy annotations on the configuration class:

// Enable ASPECTJ Auto proxy @Configuration @enableaspectjautoproxy@componentscan  Public class aspectconfig {    // declaration audience Bean    @Bean    public Audience Audience () {        returnnew  audience ();}    }

If you are using XML to assemble beans, you need to use the Spring AOP namespace <aop:aspectj-autoproxy> elements:

Either way, the ASPECTJ automatic proxy creates a proxy using the @aspect annotation bean, which will match the tangent of all the facets. A proxy will be created for the bean, so that the method of notification is called before and after the pointcut.

Create a surround notification

  

@Aspect Public classAudience {//defining a named tangent point@Pointcut ("Execution (* com.spring.learn.index.Performance.perform (..))")     Public voidmypointcut () {} @Around ("Mypointcut ()")     Public voidwatchperformance (proceedingjoinpoint JP) {Try{System.out.println ("Mute the audience's phone"); System.out.println ("The audience is seated.");            Jp.proceed (); System.out.println ("A round of applause"); }Catch(Throwable e) {System.out.println ("Refund Refund"); }    }}

You can see that the wrapping method can implement all the functions of several previous annotations.

Note: The Proceedingjoinpoint parameter, this parameter must be, because it is to be called in the notification to invoke the method being notified. The notification method can do anything, and you need to call Proceedingjoinpoint's proceed () method when you want to give control to the method being notified.

Note: Be sure to call the proceed () method, or the notification will block the call to the method being notified.

In fact, you can also make multiple calls to the method being notified. This is typically done to implement retry logic.

Processing parameters in a notification

Scenario: There are multiple songs on different tracks in the tape, and calling the Playtrack () method can be used for playback. To record the number of times each track is played, use the slice to complete:

In this way, the parameters on the tangent plane can be synchronized to the notification.

Introducing new features with annotations

By introducing the AOP concept, facets can add new methods to spring beans.

We introduce the following interface for the performance interface:

 Public Interface encoreable {    void  perforencore ();}

The facets defined are as follows:

@Aspect  Public class Encoreableintroducer {    = "com.spring.learn.index.performance+",                        = Defaultencoreable. class public static  encoreable encoreable;}     

Note: As with other facets, we need to declare encoreableintroducer as a bean in the spring application:

//Enable ASPECTJ Auto proxy@Configuration @enableaspectjautoproxy@componentscan Public classAspectconfig {//declaring audience Beans@Bean PublicAudience Audience () {return Newaudience (); }        //declaring encoreableintroducer Beans@Bean Publicencoreableintroducer Encoreableintroducer () {return NewEncoreableintroducer (); }}

Or:

Since the XML configuration is no longer in touch.

So the XML configuration and ASPECTJ of the more powerful aspect-oriented implementation, and so on after a while to add.

ASPECTJ's Comprehensive Learning blog address.

The content of this article is the content of the book with their own personal views. There may be many problems in the personal view (after all, limited knowledge, resulting in limited awareness), if the reader feel that there is a problem please bold, we can communicate with each other, learn from each other, welcome your arrival, the heart becomes full, waiting for your evaluation.

Annotation-based AOP of Spring basics

Related Article

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.