千山鸟飞绝 万径人踪灭
勤练内功,不断实践招数。争取早日成为武林高手
Spring提供了两种切面声明方式,实际工作中我们可以选用其中一种:
      基于XML配置方式声明切面。
      基于注解方式声明切面。
要进行AOP编程,首先我们要在spring的配置文件中引入aop命名空间:
<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.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
</beans>


基于注解方式声明切面

@Aspect
public class LogPrint {
 @Pointcut("execution(* cn.itcast.service..*.*(..))")
 private void anyMethod() {}//声明一个切入点 
 @Before("anyMethod() && args(userName)")//定义前置通知
 public void doAccessCheck(String userName) {
 } 
 @AfterReturning(pointcut="anyMethod()",returning="revalue")//定义后置通知
 public void doReturnCheck(String revalue) {
 }
 @AfterThrowing(pointcut="anyMethod()", throwing="ex")//定义例外通知
    public void doExceptionAction(Exception ex) {
 }
 @After("anyMethod()")//定义最终通知
 public void doReleaseAction() {
 }
 @Around("anyMethod()")//环绕通知
 public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
  return pjp.proceed();
 }
}



基于基于XML配置方式声明切面


public class LogPrint {
 public void doAccessCheck() {}定义前置通知
 public void doReturnCheck() {}定义后置通知
    public void doExceptionAction() {}定义例外通知
 public void doReleaseAction() {}定义最终通知
 public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
  return pjp.proceed();环绕通知
 }
}


<bean id="orderservice" class="cn.itcast.service.OrderServiceBean"/>
<bean id="log" class="cn.itcast.service.LogPrint"/>
<aop:config>
  <aop:aspect id="myaop" ref="log">
   <aop:pointcut id="mycut" expression="execution(* cn.itcast.service..*.*(..))"/>
   <aop:before pointcut-ref="mycut" method="doAccessCheck"/>
   <aop:after-returning pointcut-ref="mycut" method="doReturnCheck "/>
   <aop:after-throwing pointcut-ref="mycut" method="doExceptionAction"/>
   <aop:after pointcut-ref="mycut" method=“doReleaseAction"/>
   <aop:around pointcut-ref="mycut" method="doBasicProfiling"/>
  </aop:aspect>
</aop:config>
 

posted on 2009-09-02 12:14 笑口常开、财源滚滚来! 阅读(2169) 评论(0)  编辑  收藏 所属分类: spring学习

只有注册用户登录后才能发表评论。


网站导航: