Spring Learning (eight) AOP Detailed

This article reference: the Spring Learning

First, an example

 

  In the example above, the landlady's core business is the contract, collect rent, then this is enough, it's part of the gray box are repeated and the edges of things, to intermediaries like, this is one of AOP idea: let the concerns of code separate from the business code!

Examples of analytical

1. Create a LandlordService [[Package] In the service class] (core business)

/ ** 
 * landlady care of business ~ (analog core business) 
 * / 
@Component ( "of the Landlord" )
 public  class LandlordService {
     public  void Service () {
         // just realized the core business functions 
        System.out.println ( "contract" ); 
        System.out.println ( "rental income" ); 
    } 
}

2. New In Package [aspect] next intermediaries [ BrokerAspect ] class (peripheral functions)

/ ** 
 * landlady not care ~ 
 * ~ intermediary service concerned (analog peripheral functions) 
 * / 
@Component 
@Aspect 
class BrokerAspect { 

    @Before ( "Execution (service.LandlordService.service * ())" )
     public  void before ( ) { 
        System.out.println ( "tenant showings band" ); 
        System.out.println ( "On price" ); 
    } 

    @After ( "Execution (* service.LandlordService.service ())" )
     public  void After () { 
        System.out.println ( "turnkey" ); 
    } 
}

3. Configure automatically injected in the applicationContext.xml, and told where to go Spring IoC container scanning both Bean

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    < Context: the Component-Scan Base-Package Penalty for = "Aspect" /> 
    < context: the Component-Scan Base-Package Penalty for = "Service" /> 

    <-! Statement to automatically create a proxy for the spring container configuration @Aspect those facets of bean, weaving section. -> 
    < AOP: AspectJ-the autoproxy /> 
    
</ Beans >

4. write test classes

public class TestSpring {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        LandlordService landlord = (LandlordService) context.getBean("landlord", LandlordService.class);
        landlord.service();
    }
}

5. Check the results

Second, the use annotations to develop Spring AOP

Step One: Select the connection point

  Spring is the method level AOP framework, we are also in a major amount of a class method as a connection point, another way of saying that is: Which method to choose which type of enhancement.

    ....
     public  void -Service () {
         // just implements the core business functions 
        System.out.println ( "contract" ); 
        System.out.println ( "rental income" ); 
    } 
    ....

  Here LandlordService class selecting the service () method as a connection point.

Step 2: Create section

  Choose a good connection point can create section, we can cut understood as an interceptor, when the program runs to the connection point, was blocked off at the beginning of adding a method of initialization, at the end of also joined the method of destruction only, in Spring just use @Aspect annotate a class, then the Spring IoC container will think this is a slice of:

/ ** 
 * landlady not care ~ 
 * ~ intermediary service concerned (analog peripheral functions) 
 * / 
@Component 
@Aspect 
class BrokerAspect { 

    @Before ( "Execution (service.LandlordService.service * ())" )
     public  void before ( ) { 
        System.out.println ( "tenant showings band" ); 
        System.out.println ( "On price" ); 
    } 

    @After ( "Execution (* service.LandlordService.service ())" )
     public  void After () { 
        System.out.println ( "turnkey" ); 
    } 
}

PS: is defined as a section of the class is still a Bean, need @Component comment marked

The third step: the definition of tangent point

  Defines the execution of the above comments in the regular expression, Spring regular expression determined by the concrete which is to block a class which method:

execution(* service.LandlordService.service())

  Followed by an analysis of this expression:

  • Execution : When representatives will trigger execution method
  • * : Represents any type of return method
  • service.LandlordService fully qualified name of the class representatives:
  • Service () : method intercepted name

Step four: Test AOP

  Let's explore around advice, this is the most powerful of Spring AOP notice, because it integrates pre-notification and post-notification, it retains the original features of the method of connection points, and so it is powerful and flexible, so that Let's take a look:

/ ** 
 * landlady not care ~ 
 * ~ intermediary service concerned (analog peripheral functions) 
 * / 
@Component 
@Aspect 
class BrokerAspect { 

//   before and commented @Before @After annotations and corresponding methods
 //   @Before ( "Execution (* service.LandlordService.service ())")
 //   public void the before () {
 //       System.out.println ( "with tenant showings");
 //       System.out.println ( "talk about price ");
 //   }
 // 
//   @After (" Execution (* service.LandlordService.service ()) ")
 //   public void After () {
 //       System.out.println (" turnkey ");
 / /   } 

    //   use @Around annotation while completing pre-and post notifications
    @Around("execution(* service.LandlordService.service())")
    public void around(ProceedingJoinPoint joinPoint) {
        System.out.println("带租客看房");
        System.out.println("谈价格");

        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        System.out.println("交钥匙");
    }
}

  Run the test code, the result is still correct:

Third, the development using XML configuration Spring AOP

  Annotations are a very powerful thing, but based on XML developers we still need to understand, we first look at the elements that can be configured AOP:

  With the prior written annotations by the experience, and with the above table, we will rewrite the above example XML configuration is very easy (to remove all the notes):

<! - Assembly Bean -> 
< the bean name = "Landlord" class = "pojo.Landlord" /> 
< the bean ID = "Broker" class = "aspect.Broker" /> 

<! - Configure the AOP -> 
< AOP: config > 
    <-! the wHERE: in what areas (.. bags method) do increase -> 
    < AOP: pointcut the above mentioned id = "landlordPoint" 
                  expression the = "Execution (* pojo.Landlord.service ())" /> 
    <-! the What: What do enhanced -> 
    < AOP:aspect id="logAspect" ref= "Broker" > 
        <-! the when: In what occasion (method before / after / before and after) -> 
        < AOP: around pointcut-ref = "landlordPoint" Method, = "around" /> 
    </ AOP: Aspect > 
< / AOP: config >

Run the test program, see the correct result:

 

Guess you like

Origin www.cnblogs.com/riches/p/11558164.html