"Learning" Spring's AOP: annotation-based "0 configuration" approach

Source: Internet
Author: User
Tags stub

Transferred from: http://www.cnblogs.com/jbelial/archive/2012/07/20/2539123.html

AOP (Aspect Orient programming), programming for facets.

1, the basic concept of AOP:

The AOP framework is not coupled with specific code, and the AOP framework can handle specific pointcuts (Pointcut) in the execution of a program without coupling to a particular class. The AOP framework has the following characteristics:

1, the good isolation between the steps.

2, source code independence.

Terminology of AOP:

1, Aspect (CUT): Application running process of concern, the focus can be cross-cutting multiple objects, known as crosscutting concerns.

2, Pointcut (pointcut): can be inserted to enhance the processing of the connection point.

3. Joinpoint (Connection point): Explicit points in the execution of the program, such as the invocation of a method, or the throwing of an exception.

4. Advice (enhanced processing): Enhanced processing of AOP framework-specific pointcut execution

How to use an expression to define a pointcut:

1. Introduction: Add a method or field to the class being processed.

2. Target object: An object that is enhanced by the AOP framework, also known as an enhanced object. If the AOP framework is implemented through a runtime proxy, then the object is a Proxied object.

3, AOP Proxy: The object created by the AOP framework, simply put, the agent is the enhancement of the target object.

4, Weaving (Weaving): Add enhanced processing to the target object, and create an enhanced processing process is to weave in.

2, Spring's AOP support

In AOP programming, we need to do the following three parts:

1, define common components.

2. Defining Pointcuts, a pointcut can cross-cut multiple business components.

3, the definition of enhanced processing, enhanced processing is the AOP framework for ordinary business components to weave the processing action.

The key to AOP is defining pointcuts and defining enhanced processing, and spring still has the following two ways to do it:

1, based on the annotation "0 configuration" mode.

2, the use of XML configuration file management method.

3. "0 Configuration" method based on annotation

To initiate spring support for @aspectj facets configuration and to ensure that the target bean in the spring container is automatically enhanced by one or more facets, the following code must be configured under the Spring configuration file:

  

<?xml version= "1.0" encoding= "UTF-8"? ><beans    xmlns= "Http://www.springframework.org/schema/beans"    xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"     xmlns:aop= "http://www.springframework.org/ SCHEMA/AOP "    xmlns:p=" http://www.springframework.org/schema/p "    xsi:schemalocation="/http/ Www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.0.xsd    HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd " >    <!--start @aspectj Support--   <aop:aspectj-autoproxy/></beans>

However, to fully start the Spring 0 configuration feature, you will need to add the following in the configuration code:

  

<?xml version= "1.0" encoding= "UTF-8"? ><beans    xmlns= "Http://www.springframework.org/schema/beans"    xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema /context "    xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "    xmlns:p="/http/ www.springframework.org/schema/p "    xsi:schemalocation=" Http://www.springframework.org/schema/beans     http ://www.springframework.org/schema/beans/spring-beans-2.0.xsd    HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    http://www.springframework.org/schema/ Context    Http://www.springframework.org/schema/context/spring-context-3.0.xsd ">    <!-- Start @aspectj Support--   <aop:aspectj-autoproxy/></beans>

Here are the target classes for enhanced processing:

  

Package Org.service.imp;import Org.service.person;import org.springframework.stereotype.*; @Componentpublic class Chinese implements person {public    string SayHello (String name) {        //TODO auto-generated method stub        return NA Me + "Hello, Spring Aop";    }    public void Eat (String food) {        //TODO auto-generated method stub        System.out.println ("I'm eating:" + meal);    }

3.1 Defining Slice Beans

After you start @aspectj support, as long as you configure a bean with @aspect annotation in the sping container, spring will automatically recognize the bean and treat the bean as a slice.

Use @aspect to annotate a Java class that will be used as a slice bean

@Aspectpublic class aspecttest{
Define other classes of classes to tolerate ... }

3.2 Defining before enhancement processing

Use @before to annotate a method so that the method is treated as a before enhancement. When using @before annotations, you typically specify a value that specifies a cut-in expression that specifies which pointcuts the enhanced processing will be woven into.

such as: @Before ("Execution (* com.cnblogs.jbelial.*.* (..))")

The method that is labeled by it will match the execution of all the methods of all classes under the Com.cnblogs.jbelial package as a pointcut.

Such as:

Package Org.advice.before;import Org.aspectj.lang.annotation.aspect;import org.aspectj.lang.annotation.before;// Defines a facet @aspectpublic class Beforeadvicetest {    //matches all classes under the package    @Before ("Execution (* org.service.imp.*.* (..))")    public void Authority ()    {        System.out.println ("Impersonation execution permission Check");}    }

Note: You can refer to spring's "0 configuration" support for learning how to configure the spring configuration file when you define enhanced processing.

  

3.3 Defining afterreturning enhancement processing

Similar to using @before, a @afterreturning is used to annotate an enhanced processing that will be woven after the target method is properly completed. You can specify the following two constant properties when using @afterreturning annotation.

1. Pointcut/value: An expression used to specify the pointcut.

2, returning: A return value parameter name is developed, and the method that enhances the processing definition can access the return value of the target method through the parameter name.

such as: @AfterReturning (returning = "RVT", Pointcut = "Execution (* com.cnblogs.jbelial.*.* (..))");

Specifies a returning property with a value of rvt that allows a formal parameter named rvt to be used in an enhanced processing method that represents the return value of the target method.

The formal parameter name that is set by the returning property of the @AfterReturning Annotation must correspond to a formal parameter name in the enhanced processing. When the target method execution returns, the return value is passed as the corresponding parameter value into the enhanced processing method.

As follows:

Package Org.advice.afterreturning;import Org.aspectj.lang.annotation.afterreturning;import Org.aspectj.lang.annotation.Aspect; @Aspectpublic class Afterreturningadivcetest {    @AfterReturning (returning = " RVT ",            pointcut =" Execution (* org.service.imp.*.* (..)) ")    public void log (object rvt)    {        System.out.println ("Get Target method return value:" +RVT);         SYSTEM.OUT.PRINTLN ("Analog logging Function ...");}     }

3.4 Defining afterthrowing Enhancement Processing:

Afterthrowing enhanced processing is primarily used to handle unhandled exceptions in a program.

@AfterThrowing Annotation two Common properties:

> Pointcut/value: As above.

> Throwing: Specifies a return parameter name that enhances the method of processing the definition to access the exception object thrown in the target method through the formal parameter name.

such as: @AfterThrowing (throwing = "Ex", Pointcut = "Execution (* com.cnblogs.jbelial.*.* (..))")

  

3.5 After enhancement processing:

The difference between after and afterreturning:

After: Enhanced processing no matter how the target method ends, he will be woven into it. Therefore, after-enhancement processing must be prepared to handle both normal return and exception return, which is typically used to release resources.

Afterreturning: Enhanced processing will only be woven if the target method is successfully completed.

As follows:

Package Org.advice.after;import Org.aspectj.lang.annotation.aspect;import org.aspectj.lang.annotation.after;@ Aspectpublic class Afteradvicetest {        @After ("Execution (* org.service.imp.*.* (..))")        public void release ()    {        System.out.println ("Frees resources after simulation method ends ...");}    

  

3.6 Around Enhanced Processing:

Around enhanced processing can be used to weave enhanced processing before the target method is executed, and can be woven into the enhanced action after the target method is executed. At the same time, Around enhanced processing can even determine when the target method executes, how it executes, and even completely blocks the execution of the target method.

Around enhanced processing can change the parameter values of the execution target method, or it can change the return value after the execution of the target method.

When you define a Around enhancement processing method, the first parameter of the method must be a proceedingjoinpoint type, and the proceed () method that calls Proceedingjoinpoint executes the target method.

As follows:

Package org.advice.Around; Import Org.aspectj.lang.proceedingjoinpoint;import org.aspectj.lang.annotation.*; @Aspectpublic class aroundadvicetest {    @Around ("Execution (* org.service.imp.*.* (..))")    public void Processtext (Proceedingjoinpoint PJ) throws Throwable    {        System.out.println ("simulates starting a transaction before executing the target method. ");        Pj.proceed ();         SYSTEM.OUT.PRINTLN ("After executing the target method, the simulation ends the transaction. ");    }}

  

3.7 To access the parameters of the target method:

The approach to the target method is to define enhanced processing when the first parameter is defined as the Joinpoint type, and when the enhanced processing method is called, the Joinpoint parameter represents the join point for weaving the enhanced processing. The joinpoint contains the following common methods:

> object[] Getargs (): Returns the parameter when the target method is executed.

> Signature getsignature (): Returns information about the enhanced method.

> Object Gettarget (): Returns the target object that was woven into the enhanced processing.

> Object Getthis (): Returns information about the target of the AOP framework.

Note: Proceedingjoinpoint This class is a subclass of Joinpoint.

  

3.8 Defining Pointcuts:

A name for a cut-in expression that allows the name to be reused in multiple enhancement processes. Spring AOP supports only the spring Bean's method execution group as a connection point, so you can see the pointcut wrong with all the Bean methods that can match the cut-in expression.

A pointcut definition consists of two parts:

> a pointcut expression.

> A method signature that contains the name and any arguments.

As follows:

Package Org.advice.afterreturning;import org.aspectj.lang.annotation.*; @Aspectpublic class Adviceexpression {    @ Pointcut ("Execution (* org.service.imp.*.* (..))")    public void Test () {  }}

Note: The return value of the test method in the preceding code must be void, and when decorated with the private access control, only the pointcut can be used in the slice class.

Package Org.advice.afterreturning;import Org.aspectj.lang.annotation.afterreturning;import Org.aspectj.lang.annotation.Aspect; @Aspectpublic class Afterreturningadivcetest {    @AfterReturning (returning = "rvt",            pointcut = " Adviceexpression.test () ") Public    void Log (object rvt)    {        System.out.println (" Get Target method return value: "+RVT);         SYSTEM.OUT.PRINTLN ("Analog logging Function ...");}     }

  

3.9 Pointcut Indicator

Spring AOP supports only part of Aspect J's cut-in designator.

The pointcut indicators supported by Spring AOP are:

> exection: The connection point used to match the execution method,

> Within: To match a specific type of connection point, when using spring AOP, only the connection points executed by the method are matched.

As follows:

Within (org.service.imp.*)//Any connection point in IMP package

Within (Org.service.imp. *)//IMP package or any connection point in the child package

> this: Used to qualify an AOP proxy to be an instance of a specified type, to match all connection points of that object. When using spring AOP, only the connection points executed by the method can be matched.

> Target: Used to qualify the target object must be an instance of the specified type to match all the connection points of that object. When using spring AOP, only the connection points executed by the method can be matched.

As follows:

Matches all connections that implement the target object for the person interface

A connection point that is only a method executed in spring AOP

Target (Org.service.imp.Person)

> args: Used to qualify a qualified target parameter type, which requires that the parameter type be an instance of the specified type. When using spring AOP, only the connection points executed by the method can be matched.

Spring supports the use of the following roadbed operators to combine pointcut expressions.

>!! : Whenever a connection point matches any pointcut expression.

> &&:

>! : Requires that the connection point does not match the specified pointcut expression.

"Learning" Spring's AOP: annotation-based "0 configuration" approach

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.