Spring框架学习(二)

在Spring框架中的AOP的使用

其中有俩种方法可以完成我们先使用注解的方式以便于理解

   1  步骤一 加入依赖的Jar包

     2 步骤二 创建一个切面类

 

@Aspect  //注解
@Controller
public class ArithmaticCalculateaop {
        //前置通知
	@Before(value="execution( * com.zhiyou100.aop.*.*(..))")
	public void  before(JoinPoint JoinPoint) {
		Object[] args = JoinPoint.getArgs();
		String name = JoinPoint.getSignature().getName();
		System.out.println("===com.zhiyou100===="+name+"======start===result"+Arrays.asList(args));
	}
	//后置通知
	@After(value = "execution( * com.zhiyou100.aop.*.*(..))")   定义表达式
	public void  after(JoinPoint JoinPoint) {
	
		String name = JoinPoint.getSignature().getName();
		System.out.println("===com.zhiyou100===="+name+"======end===result");
		
	}
	//返回通知
	@AfterReturning(value = "execution( * com.zhiyou100.aop.*.*(..))",returning="result")
	public void cc(Object result) {
		System.out.println("============="+result);
		
	}
	@AfterThrowing(value = "execution( * com.zhiyou100.aop.*.*(..))",throwing="e")
	public void dd(Exception e) {
		System.out.println("异常了");
	}
	
}

   3 步骤三 在Spring配置文件中开启切面注解

    

     <!-- 开启包扫描 -->
     <context:component-scan base-package="com.zhiyou100.aop"/>
     <!--  开启切面注解-->
     <aop:aspectj-autoproxy/>

 基于xml的方式(可以去掉注解)

     <!-- 定义一个被通知的程序类-->
       <bean id="asd" class="com.zhiyou100.aop.ArithmaticCalculateImp"/>
    <!-- 定义切面类的bean -->
    <bean class="com.zhiyou100.aop.ArithmaticCalculateaop" id="qwe"></bean>
    <!-- 配置文件 xml -->
    <aop:config>
    <!--定义表达式   切点  -->
      <aop:pointcut expression="execution( * com.zhiyou100.aop.*.*(..))" id="zxc"/>
      <!-- 定义切面 -->
             <aop:aspect ref="qwe">
             <!--定义前置通知  -->
             <aop:before method="before" pointcut-ref="zxc"/>
             <aop:after method="after" pointcut-ref="zxc"/>
             <aop:after-returning method="cc" pointcut-ref="zxc" returning="result"/>
             </aop:aspect>
    
    </aop:config>

  

 

 

    

posted @ 2019-09-07 17:39  青灯归客  阅读(158)  评论(0编辑  收藏  举报