结合打印机的例子

要实现打印,必须要调用printer类中的print()方法

现在我希望,在print()方法执行之前,先执行---log.debug("执行了before()方法。。。");---这句话

要达到这个目的,可以直接在print()方法的最前面,加入上述语句。

当然,现在学了spring的AOP之后,有了多一个选择:通过增强配置实现

实现方法:

1.准备一个对象,里面写一个方法before(),方法里加入上面那句话

2.通过AOP把print()方法和第一步得到的方法绑定在一起.

相当于创建了一个新的类newobject,在这个类里面定义一个新的方法printBefore()

在这个方法里面,有2句话:

 before();

 print();

这个newobject对象的名字里面包含了“proxy”

上面的工作其实spring都已经帮我们做了,我们现在剩下要做的工作,只是需要告诉spring,print()方法和before()方法在哪,以及方法名就够了,

做这一步工作的方式有三种:

1.通过让before()方法去实现指定的接口,来让spring知道

剩下print()方法,通过在applicationContext.xml文件中,<aop:config><aop:pointcut expression="execution(方法定义)" />来指定

同时,告诉spring,before()方法与print()方法是一起的<aop:advisor/>

2.通过注解:

 首先在before()方法所在的类前面,加上@Aspect,表示这个类是用来增强的

 下一步,为了确认是before()方法,就在before()方法前面,加上@Before.

 然后,为了告诉spring before()方法与print()方法是一起的,需要在@Before后面加上(execution(访问控制权限 包.接口.print()))

 当然,为了应用注解,还需要在applicationContext.xml文件中做一个声明:

  <bean id="alllogger" class="cn.jbit.log.AllLogger"></bean>

  <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

3.通过schema配置切面的方式实现:

 首先定义before()方法,print()方法

 下一步,需要在applicationContext.xml文件中,加上如下语句:

  <aop:config>

  <!--* cn.jbit.print.IPrinterDAO.*(..):指定print()方法在哪个位置,以及方法名 -->

  <aop:pointcut expression="execution(* cn.jbit.print.IPrinterDAO.*(..))" id="pt"/>

  <!-- 需要指定哪个对象将要和print()方法绑定 -->

  <aop:aspect ref="alllogger">

   <!-- 还需要指定对象的哪个方法将要与print()方法绑定 -->

   <aop:before method="before" pointcut-ref="pt"/>

增强类型目前共学习了四种:

 前置增强:在print()方法执行之前要执行

 后置增强:在print()方法执行之后要执行

 环绕增强:在print()方法执行之前和之后都要执行

 异常抛出增强:当print()方法执行过程中发生异常的时候要执行