The first AOP program of Spring Learning

Source: Internet
Author: User
Tags finally block

IOC and AOP are the two cornerstones of spring, AOP (aspect-oriented programming), or plane-oriented programming, is a programming paradigm that provides an alternative perspective to program architecture to improve object-oriented programming (OOP).

In OOP development, it is based on the development of components (such as classes), and then the composition of the components, the biggest problem of OOP is the inability to decouple the components to develop, such as our above example, and AOP is to overcome this problem, it comes to the separation of this coupling. AOP provides a mechanism for developers to separate and weave crosscutting concerns (such as log concerns), separate crosscutting concerns, and then weave into the system through a technology that does not decouple our functionality.

1. Basic concepts of AOP
  • Connection point (Jointpoint): Represents an extension point that requires a crosscutting concern to be inserted in a program, which may be class initialization, method execution, method invocation, field invocation, or handling exception, and Spring only supports method execution connection points, which are represented in AOP as "where to do";
  • Pointcut (Pointcut): Select a set of related connection points, which can be considered a collection of connection points, Spring supports PERL5 regular expressions and AspectJ pointcut patterns, and spring defaults to AspectJ syntax, which is expressed in AOP as "where to do the set ";
  • Notification (Advice): The behavior performed on a connection point, which provides the means by which an AOP needs to extend existing behavior at the connection point selected by the Pointcut, including a pre-notification (before Advice), a post-notification (after Advice), surround notification (around AD Vice), AOP is implemented in Spring through proxy mode and is woven into the interceptor chain that surrounds the connection point through the interceptor pattern, which is expressed in AOP as "what to do";
  • Facets/Facets (Aspect): The modularity of crosscutting concerns can be thought of as a combination of notifications, introductions, and pointcuts, which can be implemented in Spring using Schema and @aspectj methods, and in AOP as "where to do and what to do";
  • Introduced (Inter-type declaration): Also known as an internal type declaration, adding additional new fields or methods to existing classes, Spring allows the introduction of new interfaces (which must correspond to an implementation) to all Proxied objects (target objects), expressed in AOP as "What to Do" (what to introduce) ” ;
  • Target object: An object that needs to be woven into a crosscutting concern, that is, the object that is selected by the Pointcut, the object that needs to be notified, and thus also called the "Notified Object"; Since Spring AOP is implemented through proxy mode, this object is always the proxy object, in the AOP "Who is to do";
  • AOP Proxy: An AOP framework uses the object created by the proxy pattern to insert a notification at a connection point (that is, to apply a slice), or to apply a slice to the target object through an agent. In spring, an AOP proxy can be implemented with a JDK dynamic proxy or CGLIB proxy, while a slice is applied through the interceptor model.
  • Weaving (Weaving): Weaving is a process of applying facets to a target object to create an AOP proxy object, which can be performed at compile time, class load time, and run time.
What types of notifications do spring have?
    • Pre-notification (before Advice): A notification that is executed before the method at the connection point selected by the Pointcut, which does not affect the normal program execution process (unless the notification throws an exception, the exception will break the execution of the current method chain and return).
    • Post notification (after Advice): A notification that is executed after the method at the connection point selected by the Pointcut, including the following types of post-notification:
      • Back-to-back notification (after returning Advice): The notification that is executed when the method at the connection point selected at the Pointcut is completed properly, must be the method at the connection point to invoke the post notification only if no exception is thrown on the normal return.
      • Post-exception notification (after throwing Advice): The notification that is executed when the method throws an exception on the connection point selected at the Pointcut, must be the method at the connection point that throws any exception to return when the exception notification is called.
      • Post final notification (after finally Advice): A notification executed when the method on the connection point selected at the Pointcut is returned, regardless of whether the thrown exception is executed, similar to the finally block in Java.
    • Surround notification (Around advices): A notification that surrounds the method at the connection point selected at the Pointcut, wrapping notifications can customize any behavior before and after the method call, and can decide whether to execute the method at the connection point, replace the return value, throw an exception, and so on.

In AOP, the connection point of the target object is selected through a pointcut, and then the notification is woven at the corresponding connection point of the target object, while the pointcut and the notification are the facets (crosscutting concerns), and the application of the slice at the target object connection point is implemented through an AOP proxy object.

2. HelloWorld Program of AOP

The AOP proxy is the object created by the AOP framework through the proxy pattern, Spring uses the JDK dynamic proxy or the CGLIB proxy, and spring defaults to the JDK dynamic proxy, so that any interface can be proxied, and if the object implementation of the proxy is not the interface will default to use the CGLIB proxy , but the CGLIB agent can of course be applied to the interface. The purpose of an AOP proxy is to weave slices into the target object.

Create a new project, import the corresponding package in spring, and finally introduce the jar package as shown below (some packages are not available under spring Lib and need to be downloaded separately):

(1) Define the target interface

Package Com.log;public interface Ihelloworldservice {public    void SayHello ();

(2) Define the target interface implementation class

Package Com.log;public class HelloWorldService implements Ihelloworldservice {    @Override public    void SayHello ( {        System.out.println ("---hello World---");}    }

(3) Defining the Slice support class

Package Com.log;public class Helloworldaspect {public    void Beforeadvice () {        System.out.println ("---before Advice---");    }        public void Afteradvice () {        System.out.println ('---after advice---');}    }

(4) Configuring in XML

<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.spr Ingframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http: WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-2.0.xsd "> <! --Configuration target class--<bean id= "HelloWorldService" class= "Com.log.HelloWorldService"/> <!--configuration Facets---<be An id= "aspect" class= "Com.log.HelloWorldAspect"/> <aop:config> <aop:pointcut id= "Pointcut" Expressio n= "Execution (* com.log). *.*(..))" /> <!--aop:aspect Ref reference Facets support class method--<aop:aspect ref= "aspect" > <aop:before poin                tcut-ref= "Pointcut" method= "Beforeadvice"/> <aop:after pointcut-ref= "Pointcut" Method= "Afteradvice"/> </aop:aspect> </aop:config></beans> 

The pointcut uses the <aop:pointcut> configuration under the <aop:config> tab, the expression attribute is used to define the pointcut pattern, and the default is the ASPECTJ syntax, "Execution (* cn.javass). *.*(..))” Represents the matching Cn.javass package and any method execution under the child package. For information about how the expression property is configured, click: Expression Configuration

The slice uses the <aop:aspect> tag configuration under the <aop:config> tab, where "ref" is used to refer to the method of the slice support class.
The pre-notification is defined using the <aop:before> tag under the <aop:aspect> tab, and the Pointcut-ref property is used to refer to the pointcut bean, and method is used to refer to the methods in the implementation class of the slice notification implementation , which is the method that is called before the target class method executes.
The final notification is defined using the <aop:after > tag under the <aop:aspect> tab, and in addition to using the Pointcut-ref property to refer to an existing pointcut, you can also use the Pointcut property to define such as pointcut= "Execution (* cn.javass). * * (..)) ", the method property is also a specified notification implementation, that is, the methods that are called after the target class method executes.

(5) test run

 PackageCom.log;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classAoptest { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("Aopbean.xml"); Ihelloworldservice Hello= Context.getbean ("HelloWorldService", Ihelloworldservice.class);                Hello.sayhello (); Helloworldaspect Advice= Context.getbean ("aspect", Helloworldaspect.class);    Advice.beforeadvice (); }}

(6) Output results

Resources

1, follow me to learn Springmvc directory summary paste, pdf download, source download

2, spring learning the first Hello World program

The first AOP program of Spring Learning

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.