A summary and case study of "Spring" AOP based on XML configuration

Source: Internet
Author: User
Tags call back finally block

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

First, some concepts of AOP

AOP (aspect-oriented programming, aspect-oriented programming) can be said to complement and improve OOP (object-oriented programing, object-oriented programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior. When we need to introduce public behavior to scattered objects, oop seems powerless. In other words, OOP allows you to define relationships from top to bottom, but it is not appropriate to define left-to-right relationships. such as logging capabilities. Log code is often spread horizontally across all object hierarchies, and has nothing to do with the core functionality of the objects it spreads to. This is true for other types of code, such as security, exception handling, and transparent persistence. This irrelevant code scattered around is called crosscutting (cross-cutting) code, and in OOP design, it leads to a lot of duplication of code, rather than the reuse of individual modules.

AOP, on the contrary, uses a technique called "crosscutting" that splits the encapsulated object interior and encapsulates public behavior that affects multiple classes into a reusable module, called "Aspect", or tangent. The so-called "cut-off", in short, is to encapsulate the logic or responsibility that is not related to the business, but for the common invocation of the business module, to reduce the repetitive code of the system, to reduce the coupling between modules, and to facilitate future operability and maintainability. AOP represents a horizontal relationship, if the "object" is a hollow cylinder, which encapsulates the properties and behavior of the object, then the method of plane-oriented programming is like a razor that cuts through the hollow cylinders to get inside the message. The cut-off aspect is the so-called "slice". Then it hands the cut-off slices with a clever capture of the heavens, leaving no traces.

Using "crosscutting" techniques, AOP divides software systems into two parts: core concerns and crosscutting concerns. The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. One feature of crosscutting concerns is that they often occur in many of the core concerns and are essentially similar everywhere. such as permission authentication, logging, transaction processing. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns. As Avanade's senior program architect Adam Magee says, the core idea of AOP is "separating the business logic in the application from the generic services that support it." ”

The technology of AOP can be divided into two main categories: one is to use dynamic agent technology, to decorate the message by intercepting the message, to replace the execution of the original object behavior, and to use the static weaving method to introduce the specific syntax to create "slice", so that the compiler can weave the relevant "slices" during compilation. The code. However, the technical characteristics of AOP are the same, namely:

      1, Join point: is an exact point of execution in the execution of a program, such as a method in a class. It is an abstract concept, and when implementing AOP, there is no need to define a join point.
      2, point Cut (pointcut): essentially a structure that captures the connection point. In AOP, you can define a point cut to capture calls to related methods.
      3, Advice (notification): Is the execution code for point cut, which is the specific logic for performing "facets".
      4, Aspect (tangent): Point cut and advice are combined as aspect, which resembles a class defined in OOP, but it represents more of a horizontal relationship between objects.
      5, introduce (introduced): introduces an additional method or property for an object, thus achieving the purpose of modifying the object structure. Some AOP tools refer to them as mixin.

      6, AOP Proxy: An object created by the AOP framework that can often be used as a substitute for a target object , and the AOP proxy provides more powerful functionality than the target object. The real situation is that when the application invokes the method of the AOP proxy, the AOP proxy will call back the method of the target object in its own method to complete the application invocation. A typical example of an AOP proxy is the transaction proxy bean in spring. Typically, the method of the target bean is not transactional, and the AOP proxy contains all the methods of the target bean, and these methods are strengthened into transactional methods. Simply put, the target object is the blueprint, the AOP agent is the target object's enhancement, on the target object's foundation, adds the property and the method, provides the more powerful function. The
target object contains a series of pointcuts. A pointcut can trigger a collection of processing connection points. Users can define pointcuts themselves, such as using regular expressions. The AOP agent wraps the target object and joins the processing at the pointcut. The processing that joins in the Pointcut makes the method function of the target object more powerful. Spring uses the JDK dynamic agent to implement the AOP proxy by default, primarily for the proxy interface. You can also use the Cglib proxy. Implement the proxy for the class, not the interface. If the business object does not implement an interface, the Cglib proxy is used by default. But interface-oriented programming is a good habit, try not to target specific classes of programming. Therefore, a business object should typically implement one or more interfaces.

      7, target object: An object that contains a connection point, also known as a proxy object.
      8, pre-notification (before advice): A notification that is performed before a connection point (Joinpoint), but this notification does not prevent execution before the connection point. The ApplicationContext uses <aop:before> elements to declare in <aop:aspect>.
      9, post notification (after advice): Notification that is executed when a connection point exits (whether it is a normal return or an unexpected exit). The ApplicationContext uses <aop:after> elements to declare in <aop:aspect>.
      10, after return notification (after return advice): A notification that is executed after a connection point is completed normally, and does not include cases where an exception is thrown. The ApplicationContext uses <after-returning> elements to declare in <aop:aspect>.
      11, surround notification (Around advice): A notification that surrounds a connection point, similar to the Dofilter method of the filter in the servlet specification in the Web. You can customize the behavior before and after the call to the method, or you can choose not to execute. The ApplicationContext uses <aop:around> elements to declare in <aop:aspect>.

12. Notification after an exception is thrown (after throwing advice): Notification that is executed when the method throws an unexpected exit. The ApplicationContext uses <aop:after-throwing> elements to declare in <aop:aspect>.

SPRING2.0 currently only supports the use of method calls as Connection points (join point).

Spring defines pointcut syntax: excution (modifiers-pattern? Ret-type-pattern Declaring-type-pattern? Name-pattern (Param-pattern) Throws-pattern? )

In addition to Ret-type-pattern (that is, return type mode), Name-pattern (param-pattern) (name mode and parameter mode), other modes are optional. The return type mode determines that the return type of the method must match one connection point in turn (that is, a method). One of the most frequently used return type patterns is *, which represents the matching of any return type. If the return type is indicated, such as String, then only the connection point (method) that returns the string type is matched. The name pattern matches the method name. You can use the * wildcard character to represent all method names. In the parameter pattern, () means that a method that does not accept any arguments is matched, and (.. ) represents a method that matches any number of parameters. A pattern (*) represents a method that matches any type of parameter. Pattern (*,string) indicates a match: the first is an arbitrary parameter type, and the second must be a method of type String.


ii. Schema (XML)-based AOP configuration

AOP defines facets, pointcuts, and declaration notifications from the "AOP" namespace after Spring2.0.

In the spring configuration file, so the AOP-related definition must be placed under the <aop:config> tab, which can have <aop:pointcut>, <aop:advisor>, <aop:aspect > tags, the configuration order is immutable.

    • <aop:pointcut>: Used to define the pointcut, the pointcut can be reused;
    • <aop:advisor>: A facet used to define only one notification and one pointcut;
    • <aop:aspect>: Used to define a slice that can contain multiple pointcuts and notifications, and that the notification and pointcut definitions inside the label are unordered; The advisor differs from this, with only one notification and one pointcut.


declares facets  
     facets are objects that contain pointcuts and notifications, which are defined in a spring container as a bean,xml form of a slice that requires a facet support bean that provides the state and behavior information for the slice, and the fields and methods of the support bean. and configure the way to specify pointcuts and notification implementations.  
    facets are specified using the <aop:aspect> tag, and the ref attribute is used to refer to the slice support bean.

declare pointcut  
    The pointcut is also a bean,bean definition in spring can be in three ways:  
Use <aop:pointcut> to declare a pointcut bean under <aop:config> tags, This pointcut can be used by multiple facets, preferably in a pointcut that needs to be shared, which uses the id attribute to specify the bean name, which is used by the Pointcut-ref property to refer to the pointcut in the notification definition, and the expression property to specify Pointcut expressions.  
Use <aop:pointcut> to declare a pointcut bean under the <aop:aspect> tag, which can be used by multiple slices, but generally the pointcut is used only by that slice, and of course it can be used by other facets. But it's best not to use that, the pointcut uses the id attribute to specify the bean name, use the Pointcut-ref property to refer to the pointcut through that ID when the notification definition is specified, and the expression property to specify Pointcut expressions  
  anonymous pointcut Bean, You can specify a pointcut expression through the Pointcut property when declaring a notification, which is an anonymous pointcut and is used only by that notification  

    <aop:config>         <aop:aspect ref= "Aspectsupportbean" >             <aop:after pointcut= "Execution (* Cn.javass. *.*(..))" method= "Afteradvice"/>         </aop:aspect>      </aop:config>   


Announcement Notification: (pre-notification, post-notification, surround notification)
1. Pre-notification: a notification 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).
Spring is executed before the method selected in the Pointcut, through the <aop:before> tag declaration under the <aop:aspect> tab:
    <aop:before pointcut= "pointcut expression" (or pointcut-ref= "pointcut bean Reference")            method= "forward Notification implementation method name" arg-names= "Pre-Notification implementation method parameter list parameter name" />  
pointcut and Pointcut-ref: Choose one, specify the entry point;
Method: Specify the name of the implementation of the predecessor notification, if it is polymorphic need to add parameter type, multiple with "," separated, such as Beforeadvice (java.lang.String);
Arg-names: Specifies the parameter name of the notification implementation method, multiple "," delimited, optional, and the target method parameters that use "args (param)" match in the Pointcut are automatically passed to the notification implementation method with the same name parameter.

2. Post notification: a notification executed after the method at the connection point selected by the Pointcut, including the following types of post-notification:
Back-to-back notification: The notification that is executed when the method at the connection point selected at the Pointcut has finished executing properly, must be the method at the connection point to call the post notification only if no exception is thrown at the normal return.
Execute when the method selected by the Pointcut returns normally, through the <aop:after-returning> tag declaration under the <aop:aspect> tab:
<aop:after-returning pointcut= "pointcut expression"  pointcut-ref= "pointcut Bean Reference"            method= "post-return Notification implementation method name"            arg-names= " Back-to-back notification implementation method parameter list parameter name "            returning=" the return value corresponding to the back of the return notification implementation method parameter name "    />
3, post-exception notification: the method at the connection point selected at the Pointcut throws an exception when the notification is executed, and the exception notification must be called when the method at the connection point throws any exception returned.
Execute when the method of the Pointcut selection throws an exception, through the <aop:after-throwing> tag declaration under the <aop:aspect> tab:
<aop:after-throwing pointcut= "pointcut expression"  pointcut-ref= "pointcut Bean Reference"                                    method= "post-exception Notification implementation method name"                                    arg-names= " Post exception notification implementation method parameter list parameter name "                                    
4. Post Final notification: the 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.
Executes when the method returned by the Pointcut selection is executed, whether the normal return or exception is thrown, through the <aop:after > tag declaration under the <aop:aspect> tab:
    <aop:after pointcut= "pointcut expression"  pointcut-ref= "pointcut Bean Reference"                          method= "post-final Notification implementation method name"                          arg-names= " Post-final Notification implementation method parameter list parameter name "/>   
5. Surround Notification: A notification that surrounds the method at the connection point selected at the Pointcut, wrapping notification 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.
A notification that surrounds the method at the connection point selected at the Pointcut, the surround notification is very powerful, determines whether the target method executes, when it executes, whether the method parameter needs to be replaced at execution time, and whether the return value needs to be replaced by the <aop:aspect> tab < Aop:around > Label declaration:

    <aop:around pointcut= "pointcut expression"  pointcut-ref= "pointcut Bean Reference"                             method= "post-final Notification implementation method name"                             arg-names= " Post-final Notification implementation method parameter list parameter name "/>  

surround notification The first parameter must be a org.aspectj.lang.ProceedingJoinPoint type, using the Proceedingjoinpoint proceed () method inside the notification implementation method to make the target method execute, The proceed method can pass in an optional object[] array whose value will be used as a parameter when the target method executes.

introduced
Spring allows the introduction of a new interface for the target object by using the < aop:declare-parents> tag within the < aop:aspect> tag, defined in the following way:
    <aop:declare-parents                  types-matching= "ASPECTJ syntax type expression"                  implement-interface= introduced interface "                               default-impl=" The default implementation of the introduction interface "                  delegate-ref=" introduces the default implementation of the interface Bean reference "/>  

Advisor
The advisor represents a tangent to only one notification and one pointcut, since spring AOP is a surround notification based on the AOP interceptor model, so the advisor is introduced to support various types of notifications (such as 5 of the preceding notifications), The advisor concept comes from Spring1.2 support for AOP, and there is no corresponding concept in ASPECTJ.
Advisors can use the <aop:advisor> tag definition under the <aop:config> tab:

    <aop:advisor pointcut= "pointcut expression" pointcut-ref= "pointcut Bean Reference"                             advice-ref= "notification API implementation Reference"/>            <bean id= " Beforeadvice "class=" Cn.javass.spring.chapter6.aop.BeforeAdviceImpl "/>      <aop:advisor pointcut=" Execution (* cn.javass). *.sayadvisorbefore (..)) "                             advice-ref= "Beforeadvice"/>   

iii. Examples of use


Be sure to pay attention to importing these packages!

Aspectjweaver.jar

Aopalliance-1.0.jar


1, the Human Interface class

Package com.mucfc;/**  * Functional  Person Interface class * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.24 */public interface Person {public void eatbreakfast ();p ublic void Eatlunch ();p ublic void Eatsupper ();}
2. Baby Implementation Class

Package com.mucfc;/**  * Functional  Person Implementation class * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka)  * Time 2015.4.24 */public class Babyperson implements person{@Overridepublic void Eatbreakfast () {System.out.println (" Baby is having breakfast "); @Overridepublic void Eatlunch () {System.out.println ("Baby is eating lunch"); @Overridepublic void Eatsupper () {System.out.println ("Baby is eating Dinner");}}

3, and then to enhance the method are written in a file

Package Com.mucfc;import Org.aspectj.lang.proceedingjoinpoint;public class Adivcemethod {public void beforeeat () { System.out.println ("-------------------Wash your hands before you eat!" --------------------");} public void Aftereat () {System.out.println ("-------------------take a nap after lunch! --------------------");} Public Object aroundeat (Proceedingjoinpoint pjp) throws throwable{  System.out.println ("------------------- Have a play before dinner! -------------------");    Object RetVal = Pjp.proceed ();    System.out.println ("-------------------have to go to bed after supper!" -------------------");   return retVal;}}

4, the following is the focus, the direct use of aop:config

<?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" xs i:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/sche Ma/beans/spring-beans-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework . org/schema/aop/spring-aop-3.0.xsd "> <bean id=" Babyperson "class=" Com.mucfc.BabyPerson "/><!-- Enhanced Beans--<bean id= "Adviceaspect" class= "Com.mucfc.AdivceMethod"/><!--enhancement Method Bean-- <a Op:config proxy-target-class= "true" > <aop:pointcut id= "pointcut" expression= "Execution (* Com.mucfc.BabyPerson .*(..))" /> <!--defining pointcuts-<aop:aspect ref= "Adviceaspect" > <!--defining Facets---<aop:before method= "be Foreeat "Pointcut-ref= "Pointcut"/> <!--definition of pre-enhancement Method--<aop:after method= "aftereat" pointcut= "Execution (* com.mucfc.Bab Yperson.eatlunch (..)) " /><!--definition is incremented, using anonymous pointcuts--<aop:around method= "aroundeat" pointcut= "Execution (* Com.mucfc.BabyPerson.eatS Upper (..)) " /><!--define post-increment, use anonymous pointcuts-</aop:aspect> </aop:config> </beans>

5. Testing

Package Com.mucfc;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Test {public static void main (String [] args) {ApplicationContext context=new classpathxmlapplicationcontext ("Beans.xml");       Person babyperson= (Babyperson) Context.getbean ("Babyperson");        Babyperson.eatbreakfast ();        Babyperson.eatlunch ();        Babyperson.eatsupper ();        }}
Results:

The XML-based configuration method is easy to implement, much simpler than the previous API-based approach, and the code looks easier to solve. Have to admire the power of spring!

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

A summary and case study of "Spring" AOP based on XML configuration

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.