Spring Framework in Depth (ii)--AOP face tangent

Source: Internet
Author: User
Tags aop

I. Overview of AOP

1, AOP: aspect-oriented programming, to achieve without adding code on the basis of adding some new functions (public functions);

2. AOP is not held by the spring framework, and spring is just one of the frameworks that supports AOP programming, which can be integrated with third-party frameworks for aspect-oriented programming (for example: Aspect);

3, the reality of the application scenario: the use of face-oriented programming, AOP framework has achieved a lot of facets-oriented content;

4. What programmers use AOP to do:

Write public functions, facets;

Based on the configuration of the AOP framework, the core business and the tangent plane are directly correlated;

5. There are three ways to implement AOP in spring:

Implementation based on the AspectJ annotation method

Schema-based XML configuration

Based on Proxyfactorybean agent implementation

Second, the simple implementation of AOP _ based on ASPECTJ annotations

The following steps are written:

1. Create a simple project that introduces a jar package:

  

2, writing the core business interface and implementation class

 Public Interface Serviceinterface {    publicvoid  SayHello ();      Public void Saybye ();}
/** Core Focus, core business **/@Component ("Service") Public classServiceimplImplementsServiceinterface {@Override Public voidSayHello () {//TODO auto-generated Method StubSystem.out.println ("Say Hello"); }     Public voidSaybye () {System.out.println ("Say Bye"); }}

3, write a slice class: we simply do a printout

 /*   * Public Function: Facets *  */  @Component @aspect  public  Span style= "color: #0000ff;" >class   Advicemethod { //  pre-notification  //  This method is woven into the core business:  //  @Before, which means weaving before the core business;  // Span style= "color: #008000;" >execution, indicating where the weave is located  @Before ("point ()" )  public  void      befor () {System.out.println ( log 

4. Declare this class as a tangent in the core configuration file

<!--Enable annotations -<Context:annotation-config></Context:annotation-config><!--Scan -<Context:component-scanBase-package= "Service,advice"></Context:component-scan><!--enable configuration of AOP AspectJ -<Aop:aspectj-autoproxy></Aop:aspectj-autoproxy>

5. Finally create a new test class

 Public Static void Main (string[] args) {        new classpathxmlapplicationcontext ("Applicationcontext.xml");     // to use an interface to declare a core    business class // service is a proxy object    Serviceinterface service = (serviceinterface) ac.getbean ("service");     // SayHello code does not need to change, will automatically increase the function of the log     Service.sayhello ();    Service.saybye ();}

Note: The core business class must be declared here with an interface.

In this way, a simple AOP case is built;

Third, AOP detailed

By using a crosscutting technique, the interior of the encapsulated object is analyzed, and the behavior of multiple tired behaviors is encapsulated into a reusable module, which becomes aspect and tangent.

Separating the business logic in the application from the generic services it provides support for;

1. Common terminology in AOP

(1) Facets: Description of public function and cross function

(2) Notification: Classes that implement slice functionality

(3) Target object: Notified object, object of core focus

(4) Proxy object: Agent is the target object, through the proxy target object to increase the aspect function

Target object + Slice function

The first use of a proxy object is to implement slice functionality

(5) connection point: A static concept that represents the place of notification execution

(6) Entry point: The dynamic concept, the implementation of the notification when the implementation of the section function is, the connection point becomes a point of entry;

(7) Introduction: A static concept that associates facets with target objects

(8) Weaving: Applying facets to proxy objects is a process

2. Notification type

Pre-notification: Execution before core business execution

Notification after return: execution after core business returns

Exception notification: Execution of core business when an exception occurs

Post notification: Execution after core business execution

Surround notification: Execute when core tasks are executed

The code is written as follows: how to use annotations;

@Before ("Execution (* service.*.*.* ())") Public voidbefor () {System.out.println ("Front notification, log");} @After ("Execution (* service.*.*.* ())") Public voidAfter () {System.out.println ("Post notification, execution complete");} @AfterReturning ("Execution (* service.*.*.* ())") Public voidAfterreturn () {System.out.println ("Notify after return, get return value");} @AfterThrowing ("Execution (* service.*.*.* ())") Public voidThrowexp () {System.out.println ("Exception notification, when exception is executed");} @Around ("Execution (* service.*.*.* ())") PublicObject round (Proceedingjoinpoint PJP)throwsthrowable {System.out.println ("Surround the front ... "); Object o=pjp.proceed ();//normal execution of core businessSystem.out.println ("Surround ... "); returno;}

Execution Result:

    

3. Annotations used in ASPECTJ

(1), ASPECTJ is a plane-oriented framework;

(2), spring through the ASPECTJ implementation of an annotated way to define the AOP-related configuration, reducing the dependency on the configuration file

(3), ASPECTJ provided by the note:

@AspectJ: Used on a class, declares that the class is a tangent plane;

@Before: Used on a method, declares the type of notification of the method;

@After: Used on a method, declares the type of notification of the method;

@AfterReturn: Used on a method, declares the type of notification of the method;

@AfterThrowing: Used on a method, declares the type of notification of the method;

@Around: Used on a method, declares the type of notification of the method;

@Pointcut: declaring entry points;

@Pointcut ("Execution (* service.*.*.* ())")publicvoid Point () {} @Before ( ) Publicvoid  befor () {    System.out.println ("Pre-notification, log");}

4. Use of execution expressions

AOP configuration, regardless of XML configuration, annotation configuration, used to define Pointcut pointcuts

Execution (* service.*.*.* (..))

    

5. AOP case _ based on schema

Implementing AOP Slice classes with core configuration files

<!--AOP-based configuration items provided by the AspectJ -<Aop:config>    <Aop:pointcutexpression= "Execution (* service.*.*.* (..))"ID= "PointCut"/>    <Aop:aspectID= "Myaspect"ref= "Advicemethod_xml">        <Aop:beforeMethod= "Before"Pointcut-ref= "PointCut"/>        <Aop:afterMethod= "after"Pointcut-ref= "PointCut"/>        <aop:after-returningMethod= "Afterreturn"Pointcut-ref= "PointCut"/>        <aop:after-throwingMethod= "Throwexp"Pointcut-ref= "PointCut"/>        <Aop:aroundMethod= "Round"Pointcut-ref= "PointCut"/>    </Aop:aspect></Aop:config>

The implementation effect is the same as that based on annotations;

PS: Due to the limited ability of the author, such as Error please understand

Spring Framework in Depth (ii)--AOP face tangent

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.