Spring AOP Annotation Form

Source: Internet
Author: User
Tags class definition modifiers

Aspectoriented programing, programming for facets.

AOP is mainly used for logging, performance statistics, security control (permission control), transaction processing, exception handling, etc. The code for logging, performance statistics, security control, transaction processing, exception handling, and other code is separated from the business logic code, and by separating these behaviors, we want to be able to separate them into non-instructional methods of business logic, and then change these behaviors without impacting the business logic.
Spring AOP weaves an enhancement (Advice) in two ways if the connector implements the interface using the form of the JDK's dynamic proxy, and if no interface is implemented, the dynamic bytecode generation technology (CGLIB) is used for weaving.

AOP Common terms: Connection point (Joinpoint)

Enhance the execution of a program at a specific location (where you want to do the enhanced action). Spring supports only the connection points of methods, which can be used for weaving enhancements only before method invocations, after method calls, when methods throw exceptions, and so on.

Tangent point (Pointcut)

A tangent point is a set of connection points. AOP locates specific connection points through the tangent point. The concept of database queries to understand the relationship between pointcuts and connection points is more appropriate: connection points are equivalent to records in a database, and tangency is equivalent to a query condition.

Enhanced (Advice)

Enhancement is a piece of program code that is woven into the target class connection point. Represents an action to be made on a connection point.

Facets (Aspect)

Facets consist of tangency points and enhancements (which can contain multiple pointcuts and multiple enhancements), which include both the definition of crosscutting logic and the definition of a connection point, SPRINGAOP is the framework responsible for implementing facets, which weaves the crosscutting logic defined by the facets into the link nodes specified by the facets.

Annotated Slice class Example:
@Aspect  Public class Logaspect {    @Pointcut ("Execution (* com.ctj.service.*.* (..))" )    publicvoid  pointcutname () {}    @Before ("Pointcutname ()")     publicvoid  performance () {        System.out.println ("Spring AOP");}    }

Common annotations:
    • @aspect defining Facets
    • @pointcut defining Pointcuts
    • @before Labeling the method before advice definition
    • @afterreturning labeling the method in which after returning advice is defined
    • @afterthrowing labeling the method in which after throwing advice is defined
    • @after Label The method where the After (Finally) advice definition resides
    • @around Labeling The method around advice definition

How do we specify a class of joinpoint when defining a pointcut (Pointcut)? There are two ways to specify a simple method name and a regular expression.

Common @aspectj form Pointcut expression: execution:

Spring AOP supports only joinpoint of method execution types so execution will be the most used marker we can use to help us match the joinpoint that we have in front of the specified method. The matching rules are as follows:
Execution (Modifiers-pattern return-type-pattern declaring-type-pattern? Name-pattern (Param-pattern) Throws-pattern)

    • Modifiers-pattern modifiers such as public private (can be specified without specifying)
    • Return-type-pattern return value type (must be specified)
    • Declaring-type-pattern type (can be a full path type with package name can be specified without specifying)
    • Name-pattern method Name (must be specified)
    • Param-pattern parameter type (must be specified)

The return type method name of the method and the matching pattern of the parameter part are the other parts that must be specified to be omitted.
We can also use two wildcard characters in an expression: * and.
First: * Can be used in any part of the matching pattern, matching adjacent multiple characters, i.e. a work. If the position of the method parameter is placed, the parameter is of any type.
Example: Execution (* * (String))
Second:.. Wildcards can be used in two locations where one is Declaring-type-pattern, and the other is in the location of the method parameter matching pattern.
If you place the method type, you can specify multiple levels of the type declaration. For example:
Execution (void cn.spring.*.dosomething (*)) specifies all types under cn.spring.
If it is placed in the matching position of the method parameter, it means that the method can have 0 to many parameters. For example:
Execution (void *.dosomething (..))

Within:

The within flag accepts only the type declaration, which matches all joinpoint under the specified type.
For example, within (cn.spring.aop.target.*) will match joinpoint of all types of method levels under the Cn.spring.aop.target package.

@annotation

Using the @annotation flag checks all method-level Joinpoint for all objects in the system, and if the method being instrumented has the annotation type specified by the @annotation marker, the joinpoint of the current method will be matched by the pointcut expression. For example: @pointcut ("@annotation (Com.test.aop.log.ALog)") matches all methods that use ALog annotations.

The dimensions of the matching expressions have many of the above just a few common ones, and these dimensions can be combined using | | or $$ and so on.
For example: @around ("Within (com.test.finance. *) && @annotation (com.test.finance.platform.intf.base.db.ReadOnly) ")

When defining advice, our matching dimensions can be directly written to define the method name with @pointcut, or you can directly define where you want to weave it (you can specify which methods to match directly on advice) by using the same set of definitions @joinpoint.

After defining the facets we are going to register this slice class in spring, so that spring can automatically help us weave it we also need to turn on auto-injection in the spring configuration file: <aop:aspectj-autoproxy Proxy-target-class= "true"/> so that spring can find all the methods in the IOC container to be woven into the dynamic to help us weave.

A small example of a complete spring AOP:

Business Class Code:

 Package Com.ctj.service; Import Org.springframework.stereotype.Service; @Service  Public class businessservice {    publicvoid  say () {        System.out.println ("Business Code ");}    }

Slice class definition:

 PackageCom.ctj.aspect;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Before;Importorg.aspectj.lang.annotation.Pointcut; @Aspect Public classlogaspect {@Pointcut ("Execution (* com.ctj.service.*.* (..))")     Public voidPointcutname () {} @Before ("Pointcutname ()")     Public voidperformance () {System.out.println ("Spring AOP"); }}

Spring-aop.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-3.1.xsd"><aop:aspectj-autoproxy proxy-target-class= "true"/> <bean id= "Logaspect"class= "Com.ctj.aspect.LogAspect" > </bean></beans>

Note-based spring AOP requires the JDK1.5 version to be used later, and the previous version needs to be implemented in the form of a schema-based configuration file, or if the JDK version is high, it is recommended to use annotations.

Spring AOP Annotation Form

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.