Back to Javatutorial

Spring ܵ AOP

docs/Spring全家桶/Spring/SpringAOP的概念与作用.md

1.0.014.6 KB
Original Source

Spring ܵ AOP

Spring ܵ AOP

Spring ܵһؼı(AOP)ܡıҪѳ߼ֽɲͬIJֳΪνĹע㡣һӦóĶĹܱΪйעЩйעڸ϶Ӧóҵ߼иָĺܺõӣ־¼ơʽ񡢰ȫԺͻȡ

OOP УؼԪģ࣬ AOP еԪģ档עӦó໥ϣAOP ԰ӰĶжԺйעAOP DZԵĴ Perl.NETJava ԡ

Spring AOP ģṩһӦó磬ִһʱڷִ֮ǰ֮ӶĹܡ

AOP

ǿʼʹ AOP ֮ǰϤһ AOP Щﲢض Spring AOP йصġ

Aspectһģһṩ APIs磬һ־ģΪ˼¼־ AOP áӦóӵķ棬ȡ
Join pointӦóһ㣬ڲ AOP 档Ҳ˵ʵʵӦóУһʹ Spring AOP ܡ
Adviceʵж֮ǰִ֮еķڳִڼͨ Spring AOP ʵʱõĴ롣
Pointcutһһӵ㣬֪ͨӦñִСʹñʽģʽָǽ AOP пġ
Introduction·ԵеС
Target objectһ߶֪ͨĶԶһҲΪ֪ͨ
WeavingWeaving ѷӵӦóͻ߶ϣһ֪ͨĶЩڱʱʱʱɡ

֪ͨ

Spring ʹᵽ֪ͨ

֪ͨ
ǰ֪ͨһִ֮ǰִ֪ͨ
֪ͨһִ֮󣬲ִ֪ͨ
غ֪ͨһִֻ֮ڷɹʱִ֪ͨ
׳쳣֪ͨһִֻ֮ڷ˳׳쳣ʱִ֪ͨ
֪ͨڽ鷽֮ǰִ֪֮ͨ

ʵԶ巽

Spring ֧ @AspectJ annotation style ķģʽķʵԶ巽档ַѾӽڽϸ͡

XML Schema basedʹóԼõ XML ʵֵġ
@AspectJ based@AspectJ һķΪ Java 5 ע͵ij Java ע͡

Spring л AOP XMLܹ

Ϊڱڵʹ aop ռǩҪ spring-aop ܹ

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

   <!-- bean definition & AOP specific configuration -->

</beans>

㻹ҪӦó CLASSPATH ʹ AspectJ ļЩļһ AspectJ װõ lib Ŀ¼ǿõģ Internet ǡ(עaspectjweaver.jar Ѱ)

  • aspectjrt.jar

  • aspectjweaver.jar

  • aspectj.jar

  • aopalliance.jar

һ aspect

һ aspect ʹ Ԫģֵ֧ bean ʹ ref õģʾ


   
   ...
   

<bean id="aBean" class="...">
...
</bean>

aBean úע룬ǰ½㿴 Spring bean һ

һ

һ****ȷʹòִͬеĸȤӵ㣨ڴõ XML ܹʱ㽫ᰴʾ壺


   
   
   ...
   

<bean id="aBean" class="...">
...
</bean>

ʾһΪ businessService 㣬㽫 com.tutorialspoint µ Student е getName() ƥ䣺


   
   
   ...
   

<bean id="aBean" class="...">
...
</bean>

ʹԪ͵֪ͨ£


   
      
      <!-- a before advice definition -->
      
      <!-- an after advice definition -->
      
      <!-- an after-returning advice definition -->
      <!--The doRequiredTask method must have parameter named retVal -->
      
      <!-- an after-throwing advice definition -->
      <!--The doRequiredTask method must have parameter named ex -->
      
      <!-- an around advice definition -->
      
   ...
   

<bean id="aBean" class="...">
...
</bean>

ԶԲͬĽʹͬ doRequiredTask ߲ͬķЩΪ aspect ģһ塣

AOP XML ܹʾ

ΪᵽĻ AOP XML ܹĸDZдһʾʵּ顣Ϊǵʾʹü飬ʹ Eclipse IDE ڹ״̬Ȼ²贴һ Spring Ӧó

1һΪ SpringExample ĿĿ src ļ´һΪ com.tutorialspoint İ
2ʹ Add External JARs ѡ Spring ļ Spring Hello World Example ½н͵
3Ŀ Spring AOP ָĿļ aspectjrt.jar aspectjweaver.jar aspectj.jar
4com.tutorialspoint ´ Java Logging Student MainApp
5src ļ´ Beans ļ Beans.xml
6һǴ Java ļ Bean ļݣҰ½͵Ӧó

Logging.java ļݡʵ aspect ģһʾڸõķ

package com.tutorialspoint;
public class Logging {
   /** 
    * This is the method which I would like to execute
    * before a selected method execution.
    */
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
   /** 
    * This is the method which I would like to execute
    * after a selected method execution.
    */
   public void afterAdvice(){
      System.out.println("Student profile has been setup.");
   }
   /** 
    * This is the method which I would like to execute
    * when any method returns.
    */
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }
   /**
    * This is the method which I would like to execute
    * if there is an exception raised.
    */
   public void AfterThrowingAdvice(IllegalArgumentException ex){
      System.out.println("There has been an exception: " + ex.toString());   
   }  
}

Student.java ļݣ

package com.tutorialspoint;
public class Student {
   private Integer age;
   private String name;
   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }  
   public void printThrowException(){
       System.out.println("Exception raised");
       throw new IllegalArgumentException();
   }
}

MainApp.java ļݣ

package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
      Student student = (Student) context.getBean("student");
      student.getName();
      student.getAge();      
      student.printThrowException();
   }
}

ļ Beans.xml

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

   
      
         
         
         
         
         
      
   

   <!-- Definition for student bean -->
   <bean id="student" class="com.tutorialspoint.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>      
   </bean>

   <!-- Definition for logging aspect -->
   <bean id="logging" class="com.tutorialspoint.Logging"/> 

</beans>

һѾɵĴԴļ bean ļһӦóӦóһжĻ⽫Ϣ

Going to setup student profile.
Name : Zara
Student profile has been setup.
Returning:Zara
Going to setup student profile.
Age : 11
Student profile has been setup.
Returning:11
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
.....
other exception content

һ涨 com.tutorialspoint ѡз Ǽһ£Ҫһķ֮ǰִ֮Ľ飬ͨ滻ʹʵͷƵ㶨еǺţ*ִС

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

   
   
      
      
      
   
   

   <!-- Definition for student bean -->
   <bean id="student" class="com.tutorialspoint.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>      
   </bean>

   <!-- Definition for logging aspect -->
   <bean id="logging" class="com.tutorialspoint.Logging"/> 

</beans>

ҪִͨЩ֮ʾӦó⽫Ϣ

Going to setup student profile.
Name : Zara
Student profile has been setup.
Age : 11
Exception raised
.....
other exception content

Spring л AOP @AspectJ

@AspectJ Ϊͨ Java 5 עע͵ͨ Java ָ࣬ aspects һַͨĻڼܹ XML ļаԪأ@AspectJ ֧ǿõġ

㻹ҪӦó CLASSPATH ʹ AspectJ ļЩļһ AspectJ װõ lib Ŀ¼ǿõģûУ Internet ǡ

  • aspectjrt.jar

  • aspectjweaver.jar

  • aspectj.jar

  • aopalliance.jar

һ aspect

Aspects κ bean һǽ @AspectJ ע֮⣬һзֶΣʾ

package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AspectModule {
}

ǽ XML а½ãͺκ bean һ

<bean id="myAspect" class="org.xyz.AspectModule">
   <!-- configure properties of aspect here as normal -->
</bean>

һ

һ****ȷʹòִͬеĸȤӵ㣨ڴõ XML ܹʱ֣

  • һʽǸȤĸִС

  • һǩһƺIJDzɵģʵӦǿյġ

ʾжһΪ businessService 㣬㽫 com.xyz.myapp.service µпõÿһƥ䣺

import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression 
private void businessService() {}  // signature

ʾжһΪ getname 㣬㽫 com.tutorialspoint µ Student е getName() ƥ䣺

import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.tutorialspoint.Student.getName(..))") 
private void getname() {}

ʹ @{ADVICE-NAME} עеһʾѾһǩ businessService()

@Before("businessService()")
public void doBeforeTask(){
 ...
}
@After("businessService()")
public void doAfterTask(){
 ...
}
@AfterReturning(pointcut = "businessService()", returning="retVal")
public void doAfterReturnningTask(Object retVal){
  // you can intercept retVal here.
  ...
}
@AfterThrowing(pointcut = "businessService()", throwing="ex")
public void doAfterThrowingTask(Exception ex){
  // you can intercept thrown exception here.
  ...
}
@Around("businessService()")
public void doAroundTask(){
 ...
}

Ϊһ鶨ڽ֮ǰһʾ

@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
 ...
}

AOP @AspectJ ʾ

ΪᵽĹڻ AOP @AspectJ ĸDZдһʾʵּ顣Ϊǵʾʹü飬ʹ Eclipse IDE ڹ״̬Ȼ²贴һ Spring Ӧó

1һΪ SpringExample ĿĿ src ļ´һΪ com.tutorialspoint İ
2ʹ Add External JARs ѡ Spring ļ Spring Hello World Example ½н͵
3Ŀ Spring AOP ָĿļ aspectjrt.jar aspectjweaver.jar aspectj.jar
4com.tutorialspoint ´ Java Logging Student MainApp
5src ļ´ Beans ļ Beans.xml
6һǴ Java ļ Bean ļݣҰ½͵Ӧó

Logging.java ļݡʵ aspect ģһʾڸõķ

package com.tutorialspoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
@Aspect
public class Logging {
   /** Following is the definition for a pointcut to select
    *  all the methods available. So advice will be called
    *  for all the methods.
    */
   @Pointcut("execution(* com.tutorialspoint.*.*(..))")
   private void selectAll(){}
   /** 
    * This is the method which I would like to execute
    * before a selected method execution.
    */
   @Before("selectAll()")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
   /** 
    * This is the method which I would like to execute
    * after a selected method execution.
    */
   @After("selectAll()")
   public void afterAdvice(){
      System.out.println("Student profile has been setup.");
   }
   /** 
    * This is the method which I would like to execute
    * when any method returns.
    */
   @AfterReturning(pointcut = "selectAll()", returning="retVal")
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }
   /**
    * This is the method which I would like to execute
    * if there is an exception raised by any method.
    */
   @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
   public void AfterThrowingAdvice(IllegalArgumentException ex){
      System.out.println("There has been an exception: " + ex.toString());   
   }  
}

Student.java ļݣ

package com.tutorialspoint;
public class Student {
   private Integer age;
   private String name;
   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }
   public void printThrowException(){
      System.out.println("Exception raised");
      throw new IllegalArgumentException();
   }
}

MainApp.java ļݣ

package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
      Student student = (Student) context.getBean("student");
      student.getName();
      student.getAge();     
      student.printThrowException();
   }
}

ļ Beans.xml

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

    

   <!-- Definition for student bean -->
   <bean id="student" class="com.tutorialspoint.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>      
   </bean>

   <!-- Definition for logging aspect -->
   <bean id="logging" class="com.tutorialspoint.Logging"/> 

</beans>

һѾɵĴԴļ bean ļһӦóӦóһжĻ⽫Ϣ

Going to setup student profile.
Name : Zara
Student profile has been setup.
Returning:Zara
Going to setup student profile.
Age : 11
Student profile has been setup.
Returning:11
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
.....
other exception content

ο

https://www.w3cschool.cn/wkspring https://www.runoob.com/w3cnote/basic-knowledge-summary-of-spring.html http://codepub.cn/2015/06/21/Basic-knowledge-summary-of-Spring https://dunwu.github.io/spring-tutorial https://mszlu.com/java/spring http://c.biancheng.net/spring/aop-module.html