Java SPRING-ASPECTJ

Source: Internet
Author: User

2017-11-10 21:25:02

The AspectJ AOP of spring
AspectJ is a tangent-oriented framework that extends the Java language. AspectJ defines the AOP syntax so it has a dedicated compiler to generate Class files that conform to the Java byte encoding specification.
AspectJ is an AOP framework based on the Java language, and Spring2.0 new support for AspectJ pointcut expressions
@AspectJ is a new feature of AspectJ1.5 that allows you to define facets directly in the Bean class through the JDK5 annotation technology
new version of the Spring framework, it is recommended to use the AspectJ method to develop AOP.

    • AspectJ-expression

When using the spring framework to configure AOP, the Pointcut "pointcut" needs to be defined, either through XML configuration files or annotations.

Execution (< modifier mode;? < return type mode > < method name mode > (< parameter mode >) < exception mode;?)

Other items are optional except for return type mode, method name mode, and parameter mode

Instance:

Execution (* Com.sample.service.impl). *.*(..)) The entire expression can be divided into five parts: 1, Execution (): The body of an expression. 2, the first * Number: Indicates the return type, the * number denotes all types. 3. Package Name: Indicates the package name that needs to be intercepted, and the following two periods represent all the child packages of the current package and the current package, Com.sample.service.impl the package, and the descendants of all classes. 4, the second * Number: denotes the class name, the * number denotes all classes. 5, * (..): The last asterisk denotes the method name, the * number denotes all methods, the following parentheses indicate the parameters of the method, and two periods represent any parameters. Execution ("* cn.spring3.demo1.dao.* (..)")---match only the current package execution ("* Cn.spring3.demo1.dao. *(..)”) ---the child package that matches the package and the current package. Execution (* cn.dao.genericdao+.* (..))---matching Genericdao and subclasses
Execution (* save* (..))---Match all methods of Save start
    • AspectJ Enhancement method

@Before Pre-notification, equivalent to Beforeadvice
@AfterReturning Post notification, equivalent to Afterreturningadvice
@Around Surround notification, equivalent to Methodinterceptor
@AfterThrowing Throw notification, equivalent to Throwadvice
@After Final Final notice, whether or not it is an exception, the notification will execute
@DeclareParents Referral notification, equivalent to Introductioninterceptor

One, annotation-based approach

Development steps:

    • First step: Introduce the corresponding jar package
      * ASPECTJ relies on an AOP environment.
      * Spring-aspects-3.2.0.release.jar
      * Com.springsource.org.aspectj.weaver-1.6.8.release.jar
    • Step two: Write the target class
    • Step three: Use ASPECTJ annotations to customize the slice class, which is the tangent point and the enhanced combination
    • Fourth Step: Configure XML
      * Introduction of AOP constraints:
      * <aop:aspectj-autoproxy/>---Auto-generation agent:
      * The bottom is Annotationawareaspectjautoproxycreator
Class public class Student {public    void Add () {        System.out.println ("Add Method ...");    public void Delete () {        System.out.println ("Delete method ...");}    } Slice @aspectpublic class Myaspect {    @Before ("Execution (* spring2). *.add* (..)) ")    void before () {        System.out.println ("Pre-enhancement ...");}    } Test @runwith (Springjunit4classrunner.class) @ContextConfiguration ("Classpath:config3.xml") public class Demo {    @Resource (name = "Stu")    private Student s;    @Test Public    Void Demo () {        s.add ();    }}

Configuration xml:

<?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 "Xsi:schemalocation="        Http://www.springframework.org/schema/beans http://www.springframework.org/schema/ Beans/spring-beans.xsd        HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop.xsd ">     <!--auto Generation agent, the bottom is annotationawareaspectjautoproxycreator-->    <AOP: aspectj-autoproxy/>    <bean id= "Stu" class= "Spring2". Student "/>    <!--need to register the slice class to automatically generate agents--    <bean id=" Myaspect "class=" spring2. Myaspect "/></beans>

* Other enhanced Uses:

ASPECTJ notification Type:
@Before pre-notification, equivalent to Beforeadvice
* is executed before the method. There is no way to prevent the target method from executing .
@AfterReturning post notification, equivalent to Afterreturningadvice
* post-notification, to get the method return value.
@Around surround notification, which is equivalent to Methodinterceptor
* executed before and after a method, and can prevent the execution of the target method.
@AfterThrowing throws a notification equivalent to Throwadvice
@After The final final notification, regardless of whether it is an exception, will execute
@DeclareParents Referral notification, Equivalent to Introductioninterceptor

 @Aspectpublic class Myaspect {@Before ("Execution (* spring2).    *.add* (..)) ")    void before () {System.out.println ("predecessor enhancement ..."); } @AfterReturning (value = "Execution (* spring2): *.add* (..)) ", returning =" returnval ") public void afterreturning (Object returnval) {System.out.println (" post-enhancement ").    The return value of the "+" method: "+ returnval); } @Around ("Execution (* spring2.    *.add* (..)) ")        Public Object Around (Proceedingjoinpoint proceedingjoinpoint) throws Throwable {System.out.println ("surround-before-enhance ...");        Object object = Proceedingjoinpoint.proceed ();        SYSTEM.OUT.PRINTLN ("Surround enhanced ...");    return object; } @AfterThrowing (value = "Execution (* spring2): *.add* (..)) ", throwing =" E ") public void throwing (Throwable e) {System.out.println (" bad, out of the ordinary! ")    "+ e.getmessage ()); } @After ("Execution (* spring2.    *.add* (..)) ")    public void After () {System.out.println ("final notification ..."); }}

* ASPECTJ-based pointcut definition

Use the @Pointcut to customize the pointcut definition.

@Aspectpublic class Myaspect {    @Before ("Myaspect.mypointcut ()")    Void before () {        System.out.println (" Pre-enhancement ... ");    @Pointcut ("Execution (* spring2). *.add* (..)) ")    private void Mypointcut () {}}

* The difference between advisor and aspect

Advisor:spring traditional facets: supports a tangent point and a combination of notifications.
Aspect: A combination of multiple pointcuts and multiple notifications can be supported.

Second, the XML-based approach

/** * Slice class */public class Myaspectxml {public    void before () {        System.out.println ("Pre-notification ...");    public void afterreturing (Object returnval) {        System.out.println ("Post-notification ... return value: "+ returnval);    }    Public Object Around (Proceedingjoinpoint proceedingjoinpoint) throws Throwable {        System.out.println ("surround-before-enhance ....") ;        Object result = Proceedingjoinpoint.proceed ();        SYSTEM.OUT.PRINTLN ("Surround enhanced ....");        return result;    }    public void afterthrowing (Throwable e) {        System.out.println ("Exception notification ..." + e.getmessage ());    }    public void After () {        System.out.println ("final notification ....");}    }

XML configuration:

<!--define facets--<bean id= "Myaspect" class= "spring2. Myaspect "></bean> <!--defining AOP configuration-<aop:config> <!--defining pointcuts:--<aop:poin Tcut expression= "Execution (* cn.itcast.spring3.demo2.ProductDao.add (..))" id= "Mypointcut"/> <aop:aspect ref= " Myaspect > <!--pre-notification-<!--<aop:before method= "before" pointcut-ref= "Mypointcut"/ > <!--back notification-<!--< aop:after-returning method= "afterreturing" Pointcut-re f= "Mypointcut" returning= "ReturnVal"/>-<!--surround Notifications-<!--< Aop:around method= "Around" pointcut-ref= "Mypointcut"/>-<!--exception Notifications-<!--< aop:after-throwing m Ethod= "afterthrowing" pointcut-ref= "Mypointcut" throwing= "E"/>-<!--Final Notice--&LT;AOP : After Method= "after" pointcut-ref= "Mypointcut"/> </aop:aspect> &lT;/aop:config> 

Java SPRING-ASPECTJ

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.