"Learning notes" Spring AOP annotations using summary

Source: Internet
Author: User
Spring AOP Basic Concepts
    1. is an implementation of augmented AOP in dynamic compilation period
    2. Integration with IOC, not a full-fledged slicing framework
    3. Complementary to dynamic agents
    4. There are two implementations: based on the JDK dynamic agent, Cglib
The difference between Spring AOP and ASPECTJ
    1. Spring's AOP is based on dynamic proxies, dynamically enhancing target objects, while ASPECTJ is static compile-time enhancements that need to be compiled with their own compilers, and require a loom
    2. Java code written with ASPECTJ cannot be compiled directly using Javac, and must be compiled using ASPECTJ enhanced AJC enhancement compilers, which do not conform to native Java syntax, and spring AOP conforms to Java syntax and does not require the compiler to compile , everything is handled by spring.
The difference between JDK dynamic agent and Cglib
    1. The dynamic agent of the JDK needs to implement the interface Invocationhandler
    2. Cglib does not need to implement an interface, using bytecode technology to modify the class file to inherit
    3. Spring uses the JDK dynamic proxy by default, and if no implementation interface is used Cglib
Use steps
    1. Defining Business Components
    2. Defining pointcuts (emphasis)
    3. Defining an enhanced processing method (tangent method)
Depend on

Jar package dependencies, and spring dependent

    1. Aspectjweaver.jar
    2. Aspectjrt.jar
    3. Aspectj.jar
    4. Aopalliance.jar

Maven Dependency

    <dependencies>        <!-- 有此依赖会远程下载其它相关依赖 -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>4.2.9.RELEASE</version>        </dependency>        <!-- aspectJ AOP 织入器 -->        <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjweaver</artifactId>            <version>1.8.9</version>        </dependency>    </dependencies>
Annotation Mode Development
    1. Scan aspect-Enhanced classes
<context:component-scan base-package="">    <context:include-filter type="annotation"        expression="org.aspectj.lang.annotation.Aspect"/></context:component-scan>
    1. Turn on @aspectj support<aop:aspectj-autoproxy/>
    2. Use @aspectj annotations to mark a slice class (Spring does not register a slice as a bean nor is it enhanced, but needs to be scanned)
    3. Use other annotations for development (see below)
Use of common annotations
    1. @Before: Execute before the tangent method
      • On the Enhanced method@Before("execution(* 包名.*.*(..))")
      • The above expression can be used pointcut or cut-in expression, the effect is consistent, and then no longer repeat
      • Tangent method does not participate in return value

Sample code

@Aspectpublic class AuthAspect {        //定义切点    @Pointcut("execution(* com.cnblogs.hellxz.service.*.*(..))")    public void pointCut() {}        //前置处理    @Before("pointCut()")    public void auth() {        System.out.println("模拟权限检查……");    }}
    1. @After: Executes after the tangent method
      • Usage with @before
    2. @Around: Wrapping execution outside the tangent method
      • On an enhanced method @Around("execution(* 包名.*(..))") or using a tangent point@Around("pointcut()")
      • The receive parameter type is ProceedingJoinPoint , must have this parameter in the tangent method's entry first bit
      • return value is Object
      • The proceed method of the Proceedingjoinpoint object needs to be executed, and the wrapping process before and after this method can decide when to execute with the full blocking method
      • Returns the return value of the proceed method
      • @Around equivalent to the sum of @before and @afterreturning functions
      • You can change the method parameters, which can be passed into the object[] object as arguments when the proceed method executes, used as an argument for the target method.
      • Throws an exception if the incoming object[] parameter differs from the method in the parameter or type
      • Modifies the return value of the target method by changing the return value of the proceed ()

Sample code

@Aspectpublic class TxAspect {        //环绕处理    @Around("execution(* com.cnblogs.hellxz.service.*.*(..))")    Object auth(ProceedingJoinPoint point) {                Object object = null;        try {            System.out.println("事务开启……");            //放行            object = point.proceed();            System.out.println("事务关闭……");        } catch (Throwable e) {            e.printStackTrace();        }                return object;    }}
    1. @AfterRetruning: Gets the return value and records the operation before the method returns
      • The difference between the method and the top is that the annotation has an object name that returns a value in addition to the tangent point.
      • Different two annotation parameters: returning and Pointcut, where the pointcut parameter can be a tangent expression or a tangent point
      • The parameter name defined by returning is used as the parameter name for the tangent method, and the type can be specified. If the Tangent method entry type specifies that object is unrestricted, and if it is a different type, the tangent method is entered if and only if the target method returns the same type, otherwise it will not
      • There is also a default value parameter, which overwrites the value of value if Pointcut is specified
      • Similar to @after, but @afterreturning will be woven only if the method is successfully completed, and @after no matter how the result will be woven into

Although you can get the return value, you cannot change the return value

Sample code

  @Aspectpublic class Afterreturningaspect {@AfterReturning (returning= "rvt", pointcut    = "Execution (* com.cnblogs.hellxz.service.*.* (..))") The type specified when declaring rvt qualifies the return value type of the target method, must return the specified type, or does not have a return value//RVT type is Object and the return value is not limited to the public void log (object rvt) {System.out.        println ("Get Target return value:" + rvt);    System.out.println ("Pretend to log ...");             /** * This method shows that if the return value type of the target method is the same as the type of the cut-in parameter, this method of slicing is executed * @param ITR */@AfterReturning (returning= "ITR",    pointcut= "Execution (* com.cnblogs.hellxz.service.*.* (..))")    public void Test (Integer itr) {System.out.println ("intentionally disturbing ...:" + ITR); }}
    1. @AfterThrowing: Processing before an exception is thrown, such as logging an error log
      • @AfterReturningSimilarly, there is also a pointcut and a parameter that defines the parameter name--throwing
      • It is also possible to restrict the execution of the tangent plane method through the entry of the tangent method, e.g. print only exceptions of type IOException, with no limit to the Throwable type
      • Pointcut using the same@AfterReturning
      • There is also a default value parameter, which overwrites the value of value if Pointcut is specified
      • If the exception in the target method is caught by the try catch block, the exception is completely handled by the catch block, and if no additional exception is thrown, it will still work and will not enter the afterthrowing tangent method

Sample code

@Aspectpublic class AfterThrowingAspect {    @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))")    public void pointcut() {}        /**     * 如果抛出异常在切面中的几个异常类型都满足,那么这几个切面方法都会执行     */    @AfterThrowing(throwing="ex1",             pointcut="pointcut()")    //无论异常还是错误都会记录    //不捕捉错误可以使用Exception    public void throwing(Throwable ex1) {        System.out.println("出现异常:"+ex1);    }        @AfterThrowing(throwing="ex",             pointcut="pointcut()")    //只管IOException的抛出    public void throwing2(IOException ex) {        System.out.println("出现IO异常: "+ex);    }}

The tangent method defined by PointCut in @before/@After/@Around need to be written in double quotes, e.g. @Before ("PointCut ()")

Joinpoint concept and Method description concept
    • As the name implies, connection points, weaving into enhanced processing of connection points
    • Information about the target method at the time the program is run is encapsulated in this connection point object
    • This connection point is read-only
Method description
    • Object[] getArgs(): Returns the parameter when the target method is executed
    • Signature getSignature(): Returns information about the enhanced method, e.g method name etc
    • Object getTarget(): Returns the target object that was woven into the enhanced processing
    • Object getThis(): Returns the proxy object generated by the AOP framework target object
Use
    • You can use this object to get all the details of the entire enhancement process by adding the Joinpoint object to the parameter list of the @before/@After/@AfterReturning/@AfterThrowing Modified slice method.
    • This method does not apply to @around, which can be used as a connection point Proceedingjoinpoint
Proceedingjoinpoint concept and Method description concept
    • It's a subclass of Joinpoint.
    • Basically the same as the Joinpoint concept, the difference is that it can be modified
    • When using @around, the first entry parameter must be a proceedingjoinpoint type
    • The proceed () or proceed (object[] args) method must be executed within the @around method to continue the method, otherwise it will remain in a blocked state
Method description

Proceedingjoinpoint is a subclass of Joinpoint that contains all of its methods, and there are two public methods

    • Object proceed(): Executing this method does not execute the target method
    • Object proceed(Object[] args): Executing this method does not execute the target method, and the object array parameter is used instead of the argument, and an exception is thrown if the incoming object[] parameter differs from the method into the parameter or is of a different type

      Modify the return value of the target method by modifying the return value of the proceed method

Priority level of incorporation

The highest priority is the first to be woven, and at the end of the connection point, the highest priority is finally woven into the

Spring AOP uses random weaving when two enhancements in different facets cut into the same connection point
If you want to specify a priority, there are two scenarios:

    • Let the slice class implement the org.springframework.core.Ordered interface, implement the GetOrder method, return the priority to be specified
    • Slice classes use @Order adornments to specify a priority value, the lower the value, the higher the priority
Accessing the parameters of the target method

In addition to using Joinpoint or proceedingjoinpoint to get information about the target method (including formal parameters), if you simply access the parameter, there is another way to implement

    • Add this way after Pointcut's execution expression && args(arg0,arg1)
@Aspectpublic class AccessInputArgs {    @Before("execution(* com.cnblogs.hellxz.test.*.*(..)) && args(arg0, arg1)")    public void access(String arg0, String arg1){        System.out.println("接收到的参数为arg0="+arg0+",arg1="+arg1);    }}

Note: In this way, only methods that match the number of parameters specified by the method are matched, and the type specified in the slice method restricts the target method, which does not conform to the condition and does not make the weave-in enhancement

Defining pointcuts

By defining pointcuts, we can reuse pointcuts, reduce the repetition of defining pointcut expressions, etc.
A pointcut definition consists of two parts:

    • Pointcut expression
    • Method signatures that contain names and arbitrary parameters

Use @pointcut annotations to mark a method with no parameters, no return value, plus a pointcut expression

    @Pointcut("execution(* com.cnblogs.hellxz.test.*.*(..))")    public void pointcut(){}
Pointcut indicator

Spring AOP supports 10 pointcut indicators: execution, within, this, target, args, @target, @args, @within, @annotation, beans under précis-writers ( No write @pointcut (), please note):

  • execution: An indicator of the connection point used to match the execution method.
    The usage is relatively complex, in the following format:execution(权限访问符 返回值类型 方法所属的类名包路径.方法名(形参类型) 异常类型)
    e.g. execution (public String com.cnblogs.hellxz.test.Test.access (string,string))
    Permission modifiers and exception types can be omitted, return types support wildcard characters, class names, method names support * Wildcard, method parameter support: Pass Match

  • within: A class used to qualify a connection point as belonging to a certain type.
    Within (com.cnblogs.hellxz.test.Test)
    Within (com.cnblogs.hellxz.test.)//package under Class
    Within (Com.cnblogs.hellxz.test
    .) Under the bag and under the sub-package

  • This and target: This is used for Cglib proxy types that do not implement an interface, and target is used to implement the JDK proxy target type of the interface
    Example: This (Com.cnblogs.hellxz.test.Foo)//foo does not implement the interface, using the Cglib proxy, with this
    Implemented an interface public class Foo implements bar{...}
    Target (Com.cnblogs.hellxz.test.Test)//foo implements the interface condition
  • args: Limits the parameter type of a connection point, which requires that the parameter type be an instance of the specified type.
    Args (Long)
  • @target: A connection point used to match the specified annotations of a class header
    @target (Org.springframework.stereotype.Repository)
  • @args: Used to match the parameters of a connection point, @args indicates that the class of parameters passed by the connection point at run time must have the specified annotation
    java @Pointcut("@args(org.springframework.web.bind.annotation.RequestBody)") public void methodsAcceptingEntities() {}
  • @within: Specifies that all connection points in a class that must include an annotation should be matched
    @within (Org.springframework.stereotype.Repository)
  • @annotation: Matches the connection points with the specified annotations
    @annotation (Org.springframework.stereotype.Repository)
  • Bean: Used to match the connection point within the specified bean instance, the ID or name of the incoming bean, and the use of the * wildcard character

    Tangent-point expression combinations

    Use &&, | | 、!、 three operators to combine pointcut expressions to represent relationships with or not
    execution(* com.cnblogs.hellxz.test.*.*(..)) && args(arg0, arg1)

Some of the code can refer to: my github

This article is for learning summary, if you need to specify the source

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.