Spring---AOP (annotation configuration)

Source: Internet
Author: User
Tags aop deprecated modifiers xmlns

1. Enable support for @aspectj

In addition to supporting schema configuration for AOP, spring supports annotation methods: using @aspectj-style facet declarations.

Spring does not support @aspectj-style facet declarations by default, in order to support the need to use the following configuration:

This allows spring to discover @aspectj-style facets and apply facets to the target object.


2. Declaring slices

@AspectJ-style declarative facets are very simple and are declared using @aspect annotations:

@Aspect () Public  
class aspect{...  
} 


Then, when the slice is declared as a bean in the configuration file, Spring automatically recognizes and configures the AOP:

This section is a pojo that can be used to make pointcuts and notification definitions, and then look down.


3. Declaration of entry Point

@AspectJ-style named Pointcuts are implemented using the @pointcut+ method under the Org.aspectj.lang.annotation package (the method must be a return void type).

< @Pointcut (value= "pointcut expression", ArgNames = "parameter list") Public  
void Pointcutname (...) {}  
Value:Specify the Pointcut expression (where to cut);

argNames: Specifies a named Pointcut method parameter list parameter name, which can be separated by a "," parameter that will be passed to a parameter with the same name as the notification method, such as a pointcut expression "args (param)" The parameter type specified by the parameter with the same name as the named Pointcut method will match the parameter type.

pointcutname: pointcut name, which can be used to reference the pointcut expression.

Example:
@Pointcut (value= "Execution (* cn.javass). *.sayadvisorbefore (..)) && args (param) ", argNames =" param ")  
Defines a pointcut with the name "Beforepointcut", which matches the first parameter type of the target method to the parameter type named "param" in the notification method implementation.


4. Notice of Announcement

@AspectJ-style declaration notifications also support 5 notification types:

first, the pre-notification : The use of the Org.aspectj.lang.annotation package under the @before Note statement;

 @Before (value = "Pointcut expression or named Pointcut", argNames = "argument list parameter name") value: Specifies a pointcut expression or a named pointcut;
ArgNames: Synonymous with Schema mode configuration. 
Define target interface: public interface Ihelloworldservice {public void SayHello ();  } defines the target interface implementation: public class HelloWorldService implements Ihelloworldservice {@Override public    
    void SayHello () {System.out.println ("============hello world!");  
}} package CN.JAVASS.SPRING.CHAPTER6.AOP;  

Import Org.aspectj.lang.annotation.Aspect; Define FACETS: @Aspect public class HelloWorldAspect2 {//define Pointcuts: @Pointcut (value= "Execution (* cn.javass). *.*(..))  && args (param) ", argNames =" param ") public void Beforepointcut (String param) {}//define notification: (Pre-notification) @Before (value = "Beforepointcut (param)", argNames = "param") public void Beforeadvice (String param) {System.out.println ("=======  
====before advice param: "+ param); The following configuration is configured in the Chapter6/advice2.xml configuration file: <?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://ww W.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.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-aop-3.0.xs D "> <aop:aspectj-autoproxy/> <bean id=" HelloWorldService "class=" Cn.javass. Spring.chapter6.service.impl.HelloWorldService "/> <bean id=" aspect "class=" cn.javass.spring.c Hapter6.aop.HelloWorldAspect2 "/> </beans> test code cn.javass.spring.chapter6.AopTest: @Test public void Te  
    Stannotationbeforeadvice () {System.out.println ("======================================");  
    ApplicationContext CTX = new Classpathxmlapplicationcontext ("Chapter6/advice2.xml"); Ihelloworldservice HelloWorldService = Ctx.getbean ("HelloWorldService", IHElloworldservice.class);  
    Helloworldservice.saybefore ("before");  
System.out.println ("======================================"); } outputs: ========================================== ===========before advice Param:before ============say before ======= ===================================
Facets, pointcuts, and notifications are all completed using annotations:
1) Use @aspect to declare pojo as a slice;
2) using @pointcut for naming pointcut declarations, specifying the target method the first parameter type must be java.lang.String, and for other matching methods but inconsistent parameter types will also be mismatched, by argnames = "Param" Specifies a parameter that will pass the matching target method parameter to the notification with the same name;
3) Use @before for a pre-notification declaration where value is used to define pointcut expressions or reference named Pointcuts;
4) configuration files need to use <aop:aspectj-autoproxy/> to turn on annotation style @aspectj support;
5) You need to register a slice as a bean, such as a "aspect" bean;
6) test the code exactly the same.


second, back to return notice: the use of the Org.aspectj.lang.annotation package under the @afterreturning Note statement;

@AfterReturning (  
value= "pointcut expression or named Pointcut",  
pointcut= "pointcut expression or named Pointcut",  
argnames= "argument list parameter name",  
returning= "Return value corresponds to parameter name") 


//Instance     
@AfterReturning (  
    value= "Execution (* cn.javass). *.saybefore (..)) ",  
    pointcut=" Execution (* cn.javass). *.sayafterreturning (..)) ",  
    argnames=" RetVal ", returning=" RetVal ") public  
void Afterreturningadvice (Object RetVal) {  
    System.out.println ("===========after Returning advice RetVal:" + retVal);  

Value: Specifies a pointcut expression or a named pointcut;
Pointcut: also specifies a pointcut expression or named Pointcut, Pointcut has a high priority if specified to overwrite the Value property;
ArgNames: Synonymous with schema mode configuration;
Returning: Synonymous with schema mode configuration.

third, the post-exception notification : The use of the Org.aspectj.lang.annotation package under the @afterthrowing Note statement;

@AfterThrowing (  
value= "pointcut expression or named Pointcut",  
pointcut= "pointcut expression or named Pointcut", argnames= "  
argument list parameter name",  
throwing= " The exception corresponds to the parameter name ") 

@AfterThrowing (  
    value=" Execution (* cn.javass). *.sayafterthrowing (..)) ",  
    argnames=" Exception ", throwing=" exception ") Public  
void Afterthrowingadvice ( Exception Exception) {  
    System.out.println ("===========after Throwing advice Exception:" + Exception);  
Value: Specifies a pointcut expression or a named pointcut;
Pointcut: also specifies a pointcut expression or named Pointcut, Pointcut has a high priority if specified to overwrite the Value property;
ArgNames: Synonymous with schema mode configuration;
Throwing: Synonymous with schema mode configuration.


Iv. Final Notice : Use the @after note statement under the Org.aspectj.lang.annotation package;

@After (  
value= "pointcut expression or named Pointcut",  
argnames= "parameter list parameter name")


@After (value= "Execution (* cn.javass). *.sayafterfinally (..)) ")  
public void Afterfinallyadvice () {  
    System.out.println ("===========after finally Advice");  
Value: Specifies a pointcut expression or a named pointcut;
ArgNames: Synonymous with schema mode configuration;


v. Surround notice : Use the @around note statement under the Org.aspectj.lang.annotation package;

@Around (  
value= "pointcut expression or named Pointcut",  
argnames= "parameter list parameter name")  

@Around (value= "Execution (* cn.javass). *.sayaround (..)) ")  
Public Object Aroundadvice (Proceedingjoinpoint pjp) throws Throwable {  
    System.out.println ("===========around Before advice ");  
    Object RetVal = pjp.proceed (new object[] {"Replace"});  
    System.out.println ("===========around after Advice");  
    return retVal;  
Value: Specifies a pointcut expression or a named pointcut;
ArgNames: Synonymous with schema mode configuration;


5. Introduction

The introduction of the @AspectJ-style declaration uses the @declareparents declaration under the Org.aspectj.lang.annotation package in the slice:

@DeclareParents (  
value= "ASPECTJ syntax type expression",  
Defaultimpl= introduces the default implementation class of the interface)  
private Interface Interface; 

@DeclareParents (  
value= "Cn.javass. *. Ihelloworldservice+ ", Defaultimpl=cn.javass.spring.chapter6.service.impl.introductiondservice.class)  
Value: Matches the ASPECTJ syntax type expression of the target object that needs to be introduced into the interface, and is synonymous with the types-matching attribute in the schema mode;

Private Interface Interface: Specifies the interface to be introduced, and is synonymous with the Implement-interface attribute in the schema mode;

Defaultimpl: Specifies the default implementation class that introduces the interface, which is synonymous with the Default-impl attribute in schema mode;

There is no way of defining synonymous with the Delegate-ref attribute in the schema mode;

6. AspectJ pointcut Indicator

The

Pointcut indicator is used to indicate pointcut expression purpose, where there is currently only one connection point for execution methods in spring AOP, the ASPECTJ pointcut indicator supported by spring AOP is as follows:
         execution: The connection point used to match the execution of the method;
         within: Used to match method execution within a specified type;
      & nbsp  this: The execution method used to match the type of the current AOP proxy object, note that the type of the AOP proxy object matches, which may include the introduction of the interface as well as type matching;
          Target: The execution method used to match the current target object type, note that the type of the target object matches, which does not include the introduction interface and type matching;
          Args: The method used to match the current execution of the passed parameter to the specified type;
          @within: For matching so hold the method within the specified annotation type;
    & nbsp     @target: The execution method used to match the current target object type, where the target object holds the specified annotation;
         @ Args: The arguments that are used to match the current execution of the passed parameters hold the execution of the specified annotation;
          @annotation: The method used to match the current execution method holding the specified annotation;
         bean:spring AOP extended, ASPECTJ does not have an indicator for the execution of Bean objects that match a particular name;
         reference pointcut: Indicates references to other named Pointcuts, only @apectj style support, schema style is not supported.

Note: Only the execution indicator is a unique execution match, and other indicators are used to limit the match.


6.1 Type matching syntax
First let's look at the following wildcard characters for ASPECTJ type matching:
* : Matches any number of characters;
.. : (Two dots) matches the repetition of any number of characters, such as matching any number of sub-packages in the type pattern, and matching any number of parameters in the method parameter pattern.
+: Matches a subtype of the specified type; only the suffix can be placed behind the type pattern.

java.lang.String    match String type;

java.*. String       matches the string type under any "one-level sub-package" Under the Java package
                    , such as matching java.lang.String, but does not match java.lang.ss.String

Java: *             match any type under the Java package and any sub-packages;
                    such as matching java.lang.String, java.lang.annotation.Annotation

java.lang.*ing      match any Java.lang package under the type of ING end;

java.lang.number+   matches the subtype of any number under the Java.lang package
                    , such as matching java.lang.Integer, also matching Java.math.BigInteger

6.2 matching An expression

6.2.1 Match type:

Use the following method to match

Fully qualified name of the annotation class

annotations: optional, types of annotations held on the type, such as @deprecated;
fully qualified name of class: required, can be any class fully qualified name.


6.2.2 Matching method execution :

Use the following method to match:

Note Modifiers return value type type declaration method name (parameter list) exception list

annotations: Optional, Method-held annotations, such as @deprecated;

modifiers: optional, such as public, protected;

return value type: required, can be any type mode; "*" denotes all types;

type declaration: optional, can be any type of mode;

method Name: required, you can use "*" for pattern matching;

parameter list:"()" means that the method does not have any parameters; "(..)" Indicates that a method that matches an arbitrary parameter is accepted, "(..., java.lang.String)" means that a match to the parameter that accepts the java.lang.String type ends, and that a method with any arguments can be accepted in front of it; "(Java.lang.String,..)" Represents a method that matches a parameter that accepts a java.lang.String type, and can accept any argument behind it; "(*,java.lang.string)" Represents a method that matches an argument that accepts a java.lang.String type and accepts an arbitrary type parameter in front of it;

exception list: optional, with "throws exception fully qualified Name list" declaration, the exception fully qualified name list if there are multiple "," split, such as throws Java.lang.IllegalArgumentException, Java.lang.ArrayIndexOutOfBoundsException.

Match Bean Name: You can use the Bean's ID or name to match, and you can use the wildcard character "*";


6.3 Combining Pointcut Expressions

AspectJ use and (&&), or (| | ), non-(. ) to combine pointcut expressions.

In the schema style, the escape character "&amp;&amp;" is required to use "&&" in XML To replace it, so it is inconvenient, so spring ASP provides and, or, not to replace &&, | | 、。。


6.4 Pointcut Use example

First, execution: use "Execution (method expression)" matching method execution;

Public * * (..)

Execution of any public method


* Cn.javass. Ipointcutservice.* ()

Any Cn.javass method in the Ipointcutservice interface under the packet and all sub-packages


* Cn.javass. *.*(..)
Cn.javass any method of any class under the package and all sub-packages


* (!cn.javass. ipointcutservice+). * (..)
Any method that is not a "Cn.javass packet and all sub-packages Ipointcutservice interfaces and sub-types"


* Cn.javass. Ipointcutservice+.* ()
Any Cn.javass method of Ipointcutservice interface and sub-type under the packet and all sub-packages


* (Cn.javass. Ipointcutservice+
&& java.io.serializable+). * (..)
Any method that implements the type of Ipointcutservice interface and java.io.Serializable interface under the Cn.javass package and all sub-packages


@java. lang.deprecated * * (..)
Any method that holds @java.lang.deprecated annotations


Second,within: use "within (type expression)" to match the execution of methods within the specified type;
Within (Cn.javass. *)
Any method execution under Cn.javass package and sub-package


Within (Cn.javass. ipointcutservice+)
Cn.javass any method of Ipointcutservice type and subtype under a package or all sub-packages


Third, this: use "This (type fully qualified name)" to match the current execution method of the type of AOP proxy object , note that the AOP proxy object type matches, which may include the introduction of interface methods can also match Note that the expression used in this must be a fully-qualified type, and wildcard characters are not supported;

This (Cn.javass.spring.chapter6.service.IPointcutService)
The current AOP object implements any method of the Ipointcutservice interface


This (Cn.javass.spring.chapter6.service.IIntroductionService)
The current AOP object implements any method of the Iintroductionservice interface, or it may be the introduction of an interface

target: use "target (type fully qualified name)" to match the execution method of the current target object type; Note that the target object type matches, which does not include the introduction of the interface also type matching; Note that the expression used in target must be of the type fully qualified name, Wildcard characters are not supported;

Target (Cn.javass.spring.chapter6.service.IPointcutService)
Any method that implements the Ipointcutservice interface for the current target object (non-AOP object)


Target (Cn.javass.spring.chapter6.service.IIntroductionService)
The current target object (non-AOP object) implements any method of the Iintroductionservice interface, which cannot be introduced into the interface

V.args: use "args (parameter type list)" to match the method that is currently executing to the execution method of the specified type, note that it matches the passed parameter type, is not a parameter type that matches the method signature, the parameter in the parameter type list must be of the type fully qualified name, the wildcard does not support ; args belongs to the dynamic pointcut, which is very expensive and should not be used in non-special cases;
Args (java.io.Serializable,..)
Any one that starts with an "incoming parameter type of java.io.Serializable" and can follow a method of any of the arguments of any type, the parameter type specified by args is dynamically matched at run time.



Reference Source:

"Sixth chapter" AOP 6.4 based on @aspectj aop--and I learned spring3

"Sixth chapter" the 6.5 AspectJ of AOP--Learn spring3 with me



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.