Use of Spring AOP

Source: Internet
Author: User
Tags aop object object throwable

One, add dependency (MAVEN)
<Dependency>   <groupId>Org.aspectj</groupId>   <Artifactid>Aspectjweaver</Artifactid>   <version>1.8.13</version></Dependency>
Ii. annotation-based spring AOP development

1. Define the target class interface and implementation class

/** * Interface Class */public interface Userdao {    int addUser ();} /**
* Implementation Class
*/@Repositorypublic class Userdaoimp implements Userdao { @Override public int AddUser () { System.out.println ("Add User ..."); return 6666;} }

2. Writing the Aspect class for spring AOP

@Aspect @componentpublic class Myaspect {/** * Front notification */@Before ("Execution (* com.wslook.aspect.UserDao.addUse    R (..)) ")    public void before () {System.out.println ("Pre-notification ...."); }/** * post-notification * ReturnVal, the return value after the Pointcut method executes */@AfterReturning (value= "Execution (* com.wslook.aspect.UserDao.add User (..)) ", returning =" returnval ") public void afterreturning (Object returnval) {System.out.println (" Post notification .... "+    ReturnVal); /** * Surround Notification * @param joinpoint the class that can be used to perform the pointcut * @return * @throws throwable */@Around ("Execution (*    Com.wslook.aspect.UserDao.addUser (..)) ")        Public Object Around (Proceedingjoinpoint joinpoint) throws Throwable {System.out.println ("surround notification before ....");        Object Obj= (Object) joinpoint.proceed ();        System.out.println ("Surround notice ....");    return obj; }/** * throws exception Notification * @param e */@AfterThrowing (value= "Execution (* com.wslook.aspect.UserDao.addUser (..))", t hrowing = "E") public void aftErthrowable (Throwable e) {System.out.println ("Occurrence exception: msg=" +e.getmessage ());    }/** * The method will be executed in any case */@After (value= "Execution (* com.wslook.aspect.UserDao.addUser (..))")    public void After () {System.out.println ("final notification ...."); }}

3. Writing the configuration file

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop.xsd ">    <Context:component-scanBase-package= "Com.wslook.aspect"/>    <!--automatic proxy support for starting @aspectj -    <Aop:aspectj-autoproxy/></Beans>

4. Writing test Classes

@RunWith (Springjunit4classrunner.class) @ContextConfiguration (locations= "Classpath:spring/spring-aspectj.xml") public class Userdaoaspectj {    @Autowired    Userdao Userdao;    @Test public    void Aspectjtest () {        userdao.adduser ();    }}

Operation Result:

Surround notice before .... Pre-notification .... Add user ... Surround notification after .... Final notice .... Post-notification .... 6666

II. XML-based development

1. Define a slice class

public class Myaspectxml {public    void before () {        System.out.println ("myaspectxml==== Pre-Notification");    }    public void Afterreturn (Object returnval) {        System.out.println ("Post-notification--return value:" +returnval);    }    Public Object Around (Proceedingjoinpoint joinpoint) throws Throwable {        System.out.println ("myaspectxml=====" before surround notification ");        Object object= joinpoint.proceed ();        System.out.println ("myaspectxml===== surround Notice");        return object;    }    public void afterthrowing (Throwable throwable) {        System.out.println ("myaspectxml====== Exception Notification:" + Throwable.getmessage ());    }    public void After () {        System.out.println ("myaspectxml===== Final notification: Come ");    }}

2. Write the configuration file (Spring-aspectj.xml):

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring- Aop.xsd ">    <!--Defining target Objects -    <Beanname= "Productdao"class= "COM.WSLOOK.ASPECT.USERDAOIMP"/>    <!--Defining Facets -    <Beanname= "Myaspectxml"class= "Com.wslook.aspect.MyAspectXML"/>    <!--Configure AOP Facets -    <Aop:config>        <!--Defining Pointcut Functions -        <Aop:pointcutID= "Pointcut"expression= "Execution (* com.wslook.aspect.UserDao.addUser (..))"/>        <!--define the notification order definition priority, the smaller the value the greater the priority -        <Aop:aspectref= "Myaspectxml"Order= "0">            <!--Define Notification method specifies the name of the notification methods and must specify the Pointcut function with the same pointcut in Myaspectxml -            <Aop:beforeMethod= "Before"Pointcut-ref= "Pointcut"/>            <!--Post notification returning= "ReturnVal" definition the return value must be the same as the name declared in the class -            <aop:after-returningMethod= "Afterreturn"Pointcut-ref= "Pointcut"returning= "ReturnVal"/>            <!--Surround Notifications -            <Aop:aroundMethod= "Around"Pointcut-ref= "Pointcut"/>            <!--Exception Notification throwing= "Throwable" Specifies the exception notification error information variable, which must be the same as the name declared in the class -            <aop:after-throwingMethod= "Afterthrowing"Pointcut-ref= "Pointcut"throwing= "Throwable"/>            <!--method: Methods of notification (final notification) Pointcut-ref: The Pointcut method to which notifications are applied -            <Aop:afterMethod= "after"Pointcut-ref= "Pointcut"/>        </Aop:aspect>    </Aop:config></Beans>

3. Test results:

myaspectxml==== pre-notification myaspectxml===== surround notification before add user ... myaspectxml===== Final Notice: Come on, myaspectxml=====. After surround notification post notification-return value: 6666

Third, development skills

1. Defining Pointcut Functions

/** * Use Pointcut to define the pointcut */@Pointcut ("Execution (* com.zejian.spring.springAop.dao.UserDao.addUser (..))") private void Mypointcut () {}/** * applies pointcut function */@After (value= "mypointcut ()") public void Afterdemo () {    System.out.println ("Final notice ....");

2. Aspect priority

    The
    • defines multiple notification responses in the same facet in response to the same pointcut function, in the order of declaration:
    • If multiple notification responses are defined in different slices in response to the same pointcut, the notification function in the high-priority slice class takes precedence and exits with the last execution
    • The
    • Ordered interface controls the precedence of the slice class, overrides the GetOrder method, customizes the return value, and the smaller the return value (int type) The greater the precedence.
@Aspectpublic class Aspectone implements Ordered {    /**     * Pointcut define the pointcut function *    /@Pointcut ("Execution (* Com.zejian.spring.springAop.dao.UserDao.deleteUser (..)) ")    private void Mypointcut () {}    @Before ("Mypointcut ()") Public    void Beforeone () {        System.out.println ("Forward notification: Aspectone. Execution Order 1 ");    }    @Before ("Mypointcut ()") Public    void Beforetwo () {        System.out.println ("Forward notification: Aspectone. Execution order 2 ");    }    @AfterReturning (value = "mypointcut ()") Public    void Afterreturningthree () {        System.out.println ("Post-Notification"). Aspectone. Execution Order 3 ");    }    @AfterReturning (value = "mypointcut ()") Public    void Afterreturningfour () {        System.out.println ("Post-Notification"). Aspectone. Execution Order 4 ");    }    /**     * Define priority, lower value, higher priority     * @return *    /@Override public    int GetOrder () {        return 0;}    }

Four, Pointcut indicator

1. Wildcard characters

Wildcard characters are almost ubiquitous when defining matching expressions, such as * 、.. , +, they have the following meanings:

    • .. : matches any number of parameters in the method definition, or any number of packages

      Any return value, any name, public method execution of any parameter (common * * (..)) Match all methods within (Com.zejian.dao) in all classes in the Com.zejian.dao package and its child packages. *)
    • +: Matches any subclass of a given class

      Match method Within (com.zejian.dao.daouser+) that implements all subclasses of the Daouser interface
    • *: matches any number of characters

      All methods Within (Com.zejian.service) that match all the classes in the Com.zejian.service package and its child packages. *//Match the Method Execution (* set* (int)) that starts with a set with the parameter int type and any return value.

2. Type-Signature expression

To facilitate filtering by type (such as interface, class name, package name), Spring AOP provides the within keyword. The syntax format is as follows:

Within (<type name>)

The type name is replaced with the package name or the class name, and a few examples are available.

Match all methods in all classes in the Com.zejian.dao package and its child packages @pointcut ("Within (Com.zejian.dao. *)//Match all methods in the Userdaoimpl class @pointcut ("Within (COM.ZEJIAN.DAO.USERDAOIMPL)")//Match Userdaoimpl class and all methods in its subclasses @pointcut (" Within (com.zejian.dao.userdaoimpl+)//matches all methods @pointcut ("Within (com.zejian.dao.userdao+)") of all classes that implement Userdao interfaces

3. Method signature Expression

If you want to filter according to the method signature, the keyword execution can help us, the syntax expression is as follows

Scope: Method scope, such as Public,private,protect//returnt-type: Method return value type//fully-qualified-class-name: The fully qualified name of the class in which the method is located// Parameters method parameter Execution (<scope> <return-type> <fully-qualified-class-name>.* (parameters))

The notification specified by the Pointcut function is applied to the given scope, return value type, fully qualified class name, and parameter matching methods, and the model case is given here:

Matches all methods in the Userdaoimpl class @pointcut ("Execution (* com.zejian.dao.userdaoimpl.* (..))") Matches all common methods in the Userdaoimpl class @pointcut ("Execution (public * com.zejian.dao.userdaoimpl.* (..))") Matches all public methods in the Userdaoimpl class and returns a value of type int @pointcut ("Execution" ("com.zejian.dao.userdaoimpl.* (..)")) Matches all common methods @pointcut ("Execution (public * com.zejian.dao.userdaoimpl.* (int,..)") in the Userdaoimpl class that have the first argument of type int.

4. Other indicators

  • bean:spring an AOP extension, ASPECTJ does not have a method for executing a bean object that matches a particular name for an indicator;

    Match the bean with the suffix service in the name. @Pointcut ("Bean (*service)") private void MyPointcut1 () {}
  • This: used to match the execution method of the current AOP proxy object type, note that it is the type matching of the AOP proxy object, which may include the introduction of the interface as well as type matching

    A method that matches any proxy object that implements the Userdao interface is filtered @pointcut ("This (Com.zejian.spring.springAop.dao.UserDao)") private void MyPointcut2 () {}
  • Target: The execution method used to match the current target object type;

    A method that matches any target object that implements the Userdao interface is filtered @pointcut ("Target (Com.zejian.spring.springAop.dao.UserDao)") private void MyPointcut3 () {}
  • @within: Used to match so hold the method within the specified annotation type; Note that there is a difference between within and within, which is used to match the execution of a method within a specified type;

    Matches the class that used the markerannotation annotation (note is class) @Pointcut ("@within (com.zejian.spring.annotation.MarkerAnnotation)") Private void MyPointcut4 () {}
  • @annotation (com.zejian.spring.MarkerMethodAnnotation): Method filtering based on the annotations applied

    Match the method that used the markerannotation annotation (note is the method) @Pointcut ("@annotation (com.zejian.spring.annotation.MarkerAnnotation)") private void MyPointcut5 () {}

ok~, about the expression indicator is introduced to this, we mainly care about the previous several commonly used, do not use the impression can be. At the end of this note, the pointcut indicator can be used to combine expressions with operator syntax, such as and, or, not (or &&, | |,!). ), here is a simple example:

Matches any method that implements the target object of the Userdao interface and that interface is not under the Com.zejian.dao package and its sub-packages @pointcut ("Target" ( COM.ZEJIAN.SPRING.SPRINGAOP.DAO.USERDAO)! Within (Com.zejian.dao. *) "private void MyPointcut6 () {}//matches any method that implements the target object of the Userdao interface and the method name is Adduser@pointcut (" Target ( Com.zejian.spring.springAop.dao.UserDao) &&execution (* com.zejian.spring.springAop.dao.UserDao.addUser (..)) ") private void MyPointcut7 () {}
V. Notification delivery Parameters
    • In spring AOP, except that the execution and bean indicators cannot pass parameters to the notification method, other indicators can automatically pass the matching method corresponding parameters or objects to the notification method.
    • Gets the parameter name specified by the "ArgNames" property after the matching method argument. As below, it should be noted that the args (indicator), argnames parameter names and before () methods in the parameter names must be consistent, that is, Param.
    • Passed arguments can be simple types or objects, and values are passed in only if the parameters and target methods match.
@Before (value= "args (param)", argnames= "param")//explicitly specified public    void before (int param) {        System.out.println (" Param: "+ param);    }

Of course, you can also use the args indicator directly without the Argnames declaration parameter, as follows:

@Before ("Execution (public * Com.zejian). *.adduser (..)) && args (userId,..) ")  public void before (int userId) {      ////Call AddUser's method when a parameter matching adduser is passed in and passed in    System.out.println ("UserId:" + userId);  }

Args (UserId,..) The expression guarantees that only those methods that receive at least one parameter and that the incoming type must be identical to the UserID are guaranteed to match

Reference: https://www.cnblogs.com/junzi2099/p/8274813.html

Use of Spring 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.