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-2.0.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<bean id="cc" class="cn.java.spring2.Impl2">
</bean>

<!-- 这个bean与其他bean无关,与AOP也毫无关系。所以去掉下面的aop配置不影响程序原有的功能。
一旦配置了aop,就会装载,对程序监控。
-->
<bean id="bb" class="cn.java.aop.MyTarget">
</bean>

<bean id="MyAdvice" class="cn.java.aop.MyAdvice"/>
<!-- 使用<aop:config/>的配置,在上面的声明中必须包含名字空间为xmlns:aop=""的-->
<aop:config>
      <aop:aspect ref="MyAdvice">
     
<!-- 按切入点配置的表达式对类MyTarget的方法test1()监控,只要调用运行test1()方法,
       就会触发事件。这时就会找aspect ref="MyAdvice",然后再找id="MyAdvice"
       的bean,去执行那个class(就是我们追加功能的那个类).id="xxx"的xxx是我们在下面
       <aop:around pointcut-ref="xxx" method="xxx"/>中pointcut-ref的名称。
       方法名与括号间加*表示以"test1"开头的方法。
  -->
         <aop:pointcut id="myMethod"
                    expression="execution(* cn.javass.aop.MyTarget.test1*())"/>

         <!-- 按下面配置中的before,around,after决定把我们追加的功能追加到原有方法的前面或后面,
              我们追加功能的方法的方法名在method="方法名"中配置。配置为aop:around时,需要在程序中
              用call.proceed()调用一下。
-->
         <aop:around pointcut-ref="myMethod" method="cc"/>

      </aop:aspect>
   </aop:config>

</beans>


二:我们追加功能的类写法
   package cn.java.aop;

   import org.aspectj.lang.ProceedingJoinPoint;

   public class MyAdvice {
/*
* 本类是追加功能的类,执行本类的方法时,把功能按配置中的before,around,after分别追加到
* 原来方法的不同位置(前面或后面)
*/
public Object cc(ProceedingJoinPoint call) throws Throwable {

     System.out.println("111111111111111111111111");
     /*
      * 使用配置为around要在程序中写call.proceed(),如果不写,
      * 监控到要修改的方法后,会被我们的方法全部替代,不执行原有的方法。
      */
     call.proceed();
     System.out.println("2222222222222222222222222");
     return null;
   }

   }

三:目标对象(包含连接点,即我们要监控的方法的类)的写法。
   package cn.java.aop;

   public class MyTarget {

/*
* 本类为目标对象,就是程序原有的类和实现功能的方法。
*/
public void test1(){
System.out.println("now is test1================>");
}
public void test2(){
System.out.println("now is test2================>");
}
public void test3(){
System.out.println("now is test3================>");
}
  }

四:客户端写法:
   package cn.java.aop;

   import org.springframework.context.ApplicationContext;
   import org.springframework.context.support.ClassPathXmlApplicationContext;

   public class Client {
/*
* 本类为客户端,是Spring的入口点。
*/
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[]{"applicationContext.xml"});

MyTarget t = (MyTarget)context.getBean("bb");
t.test1();
}
   }

猜你喜欢

转载自ruzhefeng.iteye.com/blog/1563784