Java programmers from the stupid birds to the rookie (74) to discuss the basic concepts and configuration of AOP in Spring (vi) Spring

Source: Internet
Author: User
Tags aop throwable

First, let's take a look at some of the conceptual terms that the official document gives us about AOP:

Slice (Aspect): A modular focus that may cross multiple objects. Transaction management is a good example of crosscutting concerns in Java application. In spring AOP, slices can be implemented using patterns or based on aspect annotations. The popular point is that we add the slice class (such as Log Class), you can understand so.

Connection point (Joinpoint): a particular point in the execution of a program, such as when a method is invoked or when an exception is handled. In spring AOP, a connection point always represents the execution of a method. In layman's parlance, the point where the tangent is added.

Notification (Advice): An action that is performed on a particular connection point in the slice. These include different types of notifications such as "Around", "before", and "after" (the type of notification will be discussed later). Many AOP frameworks, including spring, use interceptors as notification models and maintain a chain of interceptors centered on connection points.

Pointcut (Pointcut): an assertion that matches a connection point. A notification is associated with a pointcut expression and runs on a connection point that satisfies the pointcut (for example, when a method of a particular name is executed). How Pointcut expressions match connection points is at the heart of AOP: Spring defaults to using ASPECTJ pointcut syntax.

Introduction (Introduction): Used to declare an additional method or property (also known as a connection type declaration (Inter-type declaration)) for a type. Spring allows the introduction of a new interface (and a corresponding implementation) to any object that is being represented. For example, you can use the introduction to enable a bean to implement the IsModified interface to simplify caching mechanisms.

Target object: An object that is notified by one or more facets. Are called also to be informed (advised) objects. Since spring AOP is implemented through Run-time proxies, this object is always a proxy (proxied) object.

AOP Proxy: An object created by an AOP framework to implement a facet contract (for example, notification method execution, and so on). In spring, an AOP agent can be either a JDK dynamic proxy or a cglib proxy.

Weaving (weaving): Connecting slices to other application types or objects, and creating an object to be notified. These can be done at compile time (for example, using the ASPECTJ compiler), when the class is loaded, and at run time. Spring, like other pure Java AOP frameworks, completes weaving at run time.



Notification Type:

Forward notification (before advice): a notification that executes before a connection point, but this notification cannot block the execution process before the connection point (unless it throws an exception).

Post notification (after returning advice): Notification executed after a connection point completes: For example, a method does not throw any exceptions and returns normally.

Exception notification (after throwing advice): a notification that executes when a method throws an exception exit.

Final notification (after finally): notification of a connection point when it exits (whether it is a normal return or an advice exit).

Surround notification (Around Advice): A notification that surrounds a connection point, such as a method call. This is one of the most powerful types of notification. Wrapping notifications can complete custom behavior before and after a method call. It also chooses whether to continue the connection point or to return its own return value directly or throw an exception to end execution.

Surround notification is the most common type of notification. Like ASPECTJ, Spring provides all types of notifications, and we recommend that you use the simplest possible notification type to implement the functionality you need. For example, if you only need a return value of a method to update the cache, it is best to use a post notification instead of a surround notification, although the surround notification can do the same thing. The most appropriate type of notification can make the programming model simple and avoid many potential bugs. For example, you do not need to invoke the proceed () method on the Joinpoint to surround the notification, and there will be no problem with the invocation.



the implementation of Spring AOP

In spring2.5, there are two common ways to implement AOP. The first is based on the implementation of the XML configuration file, the second is based on the annotation method implementation. Next, take a concrete example to explain the use of these two ways. The example we are going to use is a registration with a username and a password, and we use AOP to implement it when the user registers the implementation before and after the data is saved, or when the exception is thrown, in which case the log is added. Here we only talk about AOP, so I just post the key code, not the irrelevant.

First, let's take a look at the Business logic service layer:

/**
 * Registerservice Implementation class
 * @author Cao Sheng Huan */Public
class Registerserviceimpl implements Registerservice {
    Private  Registerdao Registerdao;
    Public Registerserviceimpl () {}
    /** construction method with parameters *
    /Public Registerserviceimpl (Registerdao  Registerdao) {
        This.registerdao =registerdao;
    }
    public void Save (string loginname, string password) {
        registerdao.save (loginname, password);
        throw new RuntimeException ("intentionally throws an exception ....") ");
    }
      /** Set Method *
    /public void Setregisterdao (Registerdao registerdao) {
        This.registerdao = Registerdao;
}}


For a business system, the Registerserviceimpl class is the target implementation class, and its business methods, such as before or after the Save () method, or where the code will appear to be abnormal, are AOP connection points.

The following is the code for the Log service class:


/** * Log Slice class * @author Cao Sheng Huan */public class Logaspect {//Any notification method can define the first parameter as Org.aspectj.lang.JoinPoint type public
        void before (Joinpoint call) {//Get the target object's corresponding class name String ClassName = Call.gettarget (). GetClass (). GetName ();
        Gets the method name String methodname = Call.getsignature () that is executing on the target object. GetName ();
    SYSTEM.OUT.PRINTLN ("predecessor Notice:" + className + "class" + MethodName + "method started");
    public void Afterreturn () {System.out.println ("Post notification: Method ends normally");
    public void After () {System.out.println ("Final Notice: no matter whether the method is performed properly, it will return");
    public void afterthrowing () {System.out.println ("Notification after exception is thrown: unexpected when method executes"); The method used for wrapping notifications can be defined as the first parameter as the Org.aspectj.lang.ProceedingJoinPoint type public Object doaround (proceedingjoinpoint call) th
        Rows Throwable {Object result = null;
            This.before (call);//corresponds to the predecessor notification try {result = Call.proceed (); This.afterreturn ();
  Equivalent to post notification} catch (Throwable e) {          This.afterthrowing ();
        Equivalent to the exception thrown after the notification throw e;  }finally{This.after ();
    Equivalent to final notice} return result; }
}


This class belongs to the business service class, which, if used in AOP terms, is a slice class that defines many notifications. Before (), Afterreturn (), after () and afterthrowing () are notifications.

Here we look at the specific configuration, first look at:

<1> AOP implementation based on XML configuration files: This approach has 4 steps when implementing AOP.

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:x Si= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:s chemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring -beans-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop- 2.5.xsd> <bean id= "Registerdaoimpl" class= "Com.zxf.dao.RegisterDaoImpl"/> <bean id= "Registerservice" C
    lass= "Com.zxf.service.RegisterServiceImpl" > <property name= "Registerdaoimpl" ref= "Registerdaoimpl"/> </bean> <!--log Slice class--> <bean id= "Logaspectbean" class= "Com.zxf.aspect.LogAspect"/> <! --1th Step: AOP configuration--> <aop:config> <!--2nd step: Configure a slice--> <aop:aspect id= "Logaspect" ref= "
     Logaspectbean ">       <!--step 3rd: Define pointcuts, specify Pointcut expressions--> <aop:pointcut id= "Allmethod expression=" Executio N (* com.zxf.service.*.* (..)) "
            /> <!--step 4th: Apply--> <aop:before method= "before" pointcut-ref= "Allmethod"/>
            <!--step 4th: Apply post notification--> <aop:after-returning method= "Afterreturn" pointcut-ref= "Allmethod"/> <!--4th: Application Final Notice--> <aop:after method= "after" pointcut-ref= "Allmethod"/> & lt;!
            --4th step: Notify--> <aop:after-throwing method= "afterthrowing" pointcut-ref= "Allmethod" after application throws an exception/> <!--step 4th: Apply Surround Notification--> <!--<aop:around method= "Doaround" pointcut-ref= "Allmethod"/&G
             T --> </aop:aspect> </aop:config> </beans>

The above configuration applies the front, rear, final, and notification after the pointcut has been thrown. This way, when testing the Save () method for executing the Registerserviceimpl class, the console has the following result output:

Predecessor notification: The Save method for the Com.zxf.service.RegisterServiceImpl class begins.

The Save () method in the Registerdao implementation of MySQL.

Post notification: The method ends normally.

Final notification: Whether or not the method is performed properly, it will be returned.

Now let's look at the second configuration:

<2> implementation of annotation-based AOP

Start by creating a class logannotationaspect to use as a slice, and configure this class in the spring configuration file.

The support of the JDK5.0 annotation annotation was introduced after spring2.0, providing support for ASPECTJ based on the annotation section to further simplify the configuration of AOP. There are two steps to the concrete step.

The configuration file for spring is the following configuration:

<?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-2.5.xsd
            HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http:// www.springframework.org/schema/aop/spring-aop-2.5.xsd>
    <bean id= "Registerdao" class= " Com.zxf.dao.RegisterDaoImpl "/> <bean id= registerservice" class= "Com.zxf.service.RegisterServiceImpl"
    >
        <property name= "Registerdao" ref= "Registerdao"/>
    </bean>
    <!--the Slice class is managed by the spring container- ->
    <bean id= "Logaspectbean" class= "Com.zxf.aspect.LogAnnotationAspect"/>
    <!-- Enable spring support for ASPECTJ annotations-->
    <aop:aspectj-autoproxy/>
</beans>

This is the class logannotationaspect of that slice.

/** * Log Slice class/@Aspect//Define slice class public class Logannotationaspect {@SuppressWarnings ("unused")//define Pointcut, provide a method, this
    The name of the method is the ID @Pointcut ("Execution (* com.zxf.service.*.* (..))") that changed the pointcut.
    Application of the predecessor Notification @Before ("execution (* com. zxf.service.*.* (..))") for the pointcut selected by the specified pointcut expression, private void Allmethod () {})
        public void before (Joinpoint call) {String className = Call.gettarget (). GetClass (). GetName ();
        String methodname = Call.getsignature (). GetName ();
    System.out.println ("Annotation-Front notice": "+ ClassName +" class "+ MethodName +" method started "); ///access named Pointcuts to apply the post notification @AfterReturning ("Allmethod ()") public void Afterreturn () {System.out.println ("" Annotation-
    Post Notification ": Method ends normally"); 
                //Apply the final notification @After ("Allmethod ()") public void After () {System.out.println ("annotation-Final Notice": regardless of whether the method has been performed properly, "
    + "will surely return"); The notification @AfterThrowing ("Allmethod ()") public void afterthrowing () {System.out.println () () () is thrown after applying an exception throw Post Notification ":The method is executed with an exception ");
        //apply around notification//@Around ("Allmethod ()") Public Object Doaround (Proceedingjoinpoint call) throws throwable{
        Object result = null;
            This.before (call);//corresponds to the predecessor notification try {result = Call.proceed (); This.afterreturn ();  Equivalent to post notification} catch (Throwable e) {this.afterthrowing ();
        Equivalent to the exception thrown after the notification throw e;  }finally{This.after ();
    Equivalent to final notice} return result; }
}

Note: The output is the same as the previous one.


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.