Spring Basics (3: Plane-oriented programming)

Source: Internet
Author: User

I. Plane-oriented programming

?? Spring is based on IOC and AOP, with a brief summary of the IOC and DI in the previous two sections, and a learning summary of AOP, which is a preliminary understanding of the Spring Foundation.

?? In software development, we may need something that is not business-related but must be done, such as logs, transactions, etc., which are distributed across multiple functions in the application are called crosscutting concerns, and typically crosscutting concerns are conceptually separated from the application's business logic. How to separate these crosscutting concerns from the business logic at the code level is something to be addressed by aspect-oriented programming (AOP).

? Crosscutting concerns can be described as affecting multiple applications, and facets can help us modularize crosscutting concerns. Visually presents the concept of crosscutting concerns:

On the way, Courseservice,studentservice,miscservice require accessibility features such as security and transactions, which are referred to as crosscutting concerns.

?? Inheritance and delegation are the most common object-oriented techniques for implementing the common functionality of reuse. However, using the same base class inheritance throughout your program often results in a fragile object architecture, while using delegates may require complex calls to delegate objects.

? Facets provide an alternative to inheritance and delegation, and are clearer and more concise. In aspect-oriented programming, we still define common functionality in one place, but we can declaratively define the way in which the feature is applied, without modifying the affected classes, and the affected classes are not fully aware of the presence of facets.

Two. Common terminology for AOP

?? The following are commonly used nouns in AOP.

1. Notice (Advice)

?? Notifications define what facets are and when to use them. Out of the work to be done describing the facets, the notification also solves the issue of when to perform the work. The following 5 types of notifications can be applied to sping facets.

    • before call notification before the method is called
    • After after the method completes, the notification is invoked, regardless of whether the method executes successfully
    • after-returning Call notification after the method executes successfully
    • after-throwing Call notification after method throws an exception
    • The Around Notification Wraps the method that is notified before the method call is notified and executes after the call
2. Connection point (Joinpoint)

?? Applications may have a number of opportunities to apply notifications, which are called connection points. A connection point is a point at which an application can insert a slice during execution, which can be when a method is called, when an exception is thrown, or even when a field is modified. Cut-off code can take advantage of these into the normal process of application and add new behaviors.

3. Pointcut (Pointcut)

?? A tangent point defines one or more connection points that the notification is to be woven into. If a notification defines " what " and " when " of a slice, the pointcut defines " where ". You typically use explicit class and method names to specify Pointcuts, or you can use regular expressions to define matching classes and methods to specify these pointcuts. Some AOP frameworks allow us to create dynamic pointcuts that can be used more at runtime to determine whether notifications are applied.

4. Facets (Aspect)

?? Facets are a combination of notifications and pointcuts. Notifications and Pointcuts define the entire content of the slice, what it is , when and where it will function.

5. Introduction

?? The introduction allows us to add new methods or properties to existing classes. That is, if you do not need to modify existing classes, let them have new behavior and state.

6. Weave into

?? Weaving is the process of applying facets to a target object to create a new proxy object. Facets are woven into the target object at the specified connection point, and multiple points can be woven into the target object's life cycle.

    • Compile time: Facets are woven into the target class when it is compiled. This approach requires a special compilation period, such as AspectJ's weaving compile-time
    • Class load period: Facets are woven into the target class when it is loaded into the JVM. This approach requires a special loader that can enhance the byte code of the target class before the target class is introduced to the application, such as AspectJ5 's LTW(load-time weaving)
    • Run time: Facets are woven at some point in the application's run. In general, an AOP container dynamically creates a proxy object for the target object
Three. Spring AOP

?? Spring notifies the object at run time, by wrapping the facets in the proxy class, spring will weave the facets into spring-managed beans at run time. The proxy class encapsulates the target class, intercepts calls to the method being notified, and forwards the call to the true target bean. Since spring is based on dynamic proxies, all spring supports only method connection points, and we can use aspect to assist SPRINGAOP if a connection point interception outside of the method interception is required.

?? Spring notifies the object at run time, by wrapping the facets in the proxy class, spring will weave the facets into spring-managed beans at run time. The proxy class encapsulates the target class, intercepts calls to the method being notified, and forwards the call to the true target bean. Since spring is based on dynamic proxies, all spring supports only method connection points, and we can use aspect to assist SPRINGAOP if a connection point interception outside of the method interception is required.

1. Defining pointcuts

?? In SPRINGAOP, you need to define a pointcut using AspectJ's pointcut expression language. Spring only supports partial pointcut indicators for ASPECTJ, as shown in the following table:

ASPECTJ indicator description
Arg () restrict the connection point matching parameter to the execution method of the specified type
@args () restrict the execution of connection point matching parameters by the specified annotation callout
execution () used to match the execution method of the connection point
this () restrict connection points matching the bean reference of the AOP agent as the class that guides the type
Target () restrict connection points to classes that target objects of the specified type
@target () restricts connection points to match specific execution objects that correspond to classes that have annotations of the specified type
within () restrict connection points to the specified type
@within () restrict connection points to match the type noted by the specified annotation (when using SPRINGAOP, the method is defined in the class marked by the specified annotation)
@annotation limit match with specified callout connection point
Bean () using Bean ID or Bean name as a parameter to restrict pointcuts to match only specific Bean

? Where only the execution indicator is the only execution match, the others are the limit match. So the execution indicator is

Only the execution indicator is the only execution match, and the other is the limit match. So the execution indicator is the most important indicator we use when writing a pointcut definition.

2. Writing pointcuts

?? Suppose we want to use the execution () indicator to select the SayHello () method of the Hello class, the expression is as follows:

execution(* com.test.Hello.sayHello(..))

The method expression begins with a * * number, indicating the type of the method return value. Then specify the fully qualified class name and the method name. For the method parameter list, we use () to identify the tangent point to select any SayHello () method, regardless of the method's entry parameter.

?? At the same time we can use && (and), | | (OR),! (not) to connect the indicator as follows:

execution(* com.test.Hello.sayHello(..)) and !bean(xiaobu)
3. Affirm the cut-off plane

?? The use of Proxyfactorybean in classic spring AOP is very complex, so it provides a choice of statement facets, with the following configuration elements in the Spring AOP configuration namespace:

AOP configuration Elements Description
<aop:advisor > Defining an AOP Notifier
<aop:after > Define AOP post notification (regardless of whether the method being notified is successful)
<aop:after-returning > Defining AOP after-returning Notifications
<aop:after-throwing > Define After-throwing
<aop:around > Defining AOP Surround Notifications
<aop:aspect > Defining facets
<aop:aspectj-autoproxy > Enable @aspectj annotation-driven facets
<aop:before > Defining AOP Pre-notifications
<aop:config > The top-level AOP configuration element. Most of the <aop:* > elements must be included in the
<aop:declare-parents > Introduces an additional interface to the notified object and implements it transparently
<aop:pointcut > Defining pointcuts
4. Realize

Suppose there is an actor class Actor , there is a performance method in the actor class, perform() and then there is a spectator class Audience , these two classes are under the package com.example.springtest , the main methods of the audience class are as follows:

public class Audience{    //搬凳子    public void takeSeats(){}    //欢呼    public void applaud(){}    //计时,环绕通知需要一个ProceedingJoinPoint参数    public void timing(ProceedingJoinPoint joinPoint){        joinPoint.proceed();    }    //演砸了    public void demandRefund(){}    //测试带参数    public void dealString(String word){}    }
A, XML configuration implementation

?? First configure the audience to SPRINGIOC:

<bean id="audience" class="com.example.springtest.Audience"/>

Then declare the notice:

<aop:config>  <aop:aspect ref="audience">    <!-- 申明切点 -->    <aop:pointcut id="performance" expression="execution(* com.example.springtest.Performer.perform(..))"/>    <!-- 声明传递参数切点 -->    <aop:pointcut id="performanceStr" expression="execution(* com.example.springtest.Performer.performArg(String) and args(word))"/>      <!-- 前置通知 -->    <aop:before pointcut-ref="performance" method="takeSeats"/>    <!-- 执行成功通知 -->    <aop:after-returning pointcout-ref="performance" method="applaud"/>    <!-- 执行异常通知 -->    <aop:after-throwing pointcut-ref="performance" method="demandRefund"/>    <!-- 环绕通知 -->    <aop:around pointcut-ref="performance" method="timing"/>     <!-- 传递参数 -->    <aop:before pointcut-ref="performanceStr" arg-names="word" method="dealString"/>  </aop:aspect></aop:config>
b, annotation implementation

Annotate directly on the audience class (aspect annotations are not automatically discovered and registered by spring, either written to XML, either using @aspectj annotations or adding a @component annotation), as follows:

@Aspectpublic class Audience{    //定义切点    @Pointcut(execution(* com.example.springtest.Performer.perform(..)))    public void perform(){}        //定义带参数切点    @Pointcut(execution(* com.example.springtest.Performer.performArg(String) and args(word)))    public void performStr(String word){}        //搬凳子    @Before("perform()")    public void takeSeats(){}        //欢呼    @AfterReturning("perform()")    public void applaud(){}        //计时,环绕通知需要一个ProceedingJoinPoint参数    @Around("perform()")    public void timing(ProceedingJoinPoint joinPoint){        joinPoint.proceed();    }        //演砸了    @AfterThrowing("perform()")    public void demandRefund(){}        //带参数    @Before("performStr(word)")    public void dealString(String word){}}
C. Introduce new features through facets

?? Now that you can add new functionality to an object-owned method with AOP, why not add a new method to the object? Using the AOP concept known as introduction , facets can add new methods to spring beans, as shown in the following example:

When a method that introduces an interface is called, the delegate delegates this call to some other object that implements the new interface. In fact, the implementation of the bean is split into multiple classes.

    • XML ingestion requires the use of <aop:declare-parents > elements:

      <aop:aspect>  <aop:declare-parents types-matching="com.fxb.springtest.Performer+"    implement-interface="com.fxb.springtest.AddTestInterface"    default-impl="com.fxb.springtest.AddTestImpl"/></aop:aspect>

      As the name implies &lt;declare-parents> declares that the bean notified by this slice has a new parent type in its object hierarchy. Where types-matching specifies the enhanced class, Implement-interface specifies the interface to implement the new method, Default-imple specifies the implementation class that implements the Implement-interface interface, You can also use Delegate-ref to specify a reference to a bean.

    • Annotations are introduced, through @DeclareParents annotations

      @DeclareParents(value="com.fxb.springtest.Performer+",  defaultImpl=AddTestImpl.class)public static AddTestInterface addTestInterface;

      As with XML implementations, annotations are made up of three parts: 1, the Value property is equivalent to the Tpes-matching property, identifies the enhanced class, 2, Defaultimpl equals default-imple, specifies the implementation class of the interface, 3, The static attribute labeled with the @declareparents annotation specifies the interface to be introduced.

Spring Basics (3: Plane-oriented programming)

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.