spring aop

2017-10-03  本文已影响0人  JIN520

AOP 术语

public class user{
    public void add(){...}
    public void update(){...}
    public void delete(){...}
    public void findAll(){...}
}

Advice类型:
前置通知:方法之前执行
后置通知:在方法执行之后执行
最终通知:在后置之后来执行
异常通知:方法出现异常时执行
环绕通知:方法之前和方法之后执行


AspectJ

AspectJ简介

AspectJ不是spring一部分,只是和spring一起使用进行aop操作


Spring的AOP操作

使用AspectJ实现aop的两种方式

  1. 基于AspectJ的xml配置
  2. 基于AspectJ的注解方式

AOP准备工作

xml方式

  1. 导入相关jar包
  2. 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.springframe.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
   
</beans>
  1. 示例代码
package com.zhangjinbang.aop;

public class Book{

   public void add(){
       System.out.println("add book");
   }
}

package com.zhangjinbang.aop;

public class MyBook{

    public void before1{
        System.out.println("前置增强...");
    }
}

使用表达式配置切入点

常用的表达式

execution(<访问修饰符>?<返回类型><方法名>(<参数>)<异常>)

"*" 表示的是任意的意思

常用写法

execution(* com.zhangjinbang.aop.Book.add(..))

execution(* com.zhangjinbang.aop.Book.*(..))

execution(* *.*(..))

匹配所有save开头的方法 execution(* save*(..)) 

配置文件 bean.xml

<beans xmls="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.springframe.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
       <!--配置对象-->
       <bean id="book" class="com.zhangjinbang.aop.Book"></bean>
       <bean id="myBook" class="com.zhangjinbang.aop.MyBook"></bean>
       
       <!--配置AOP操作-->
       <aop:config>
           <!--配置切入点-->
           <aop:pointcut expression="execution(* com.zhangjinbang.aop.Book.*(..))" id="pointcut1">
           <!--配置切面  把增强用到方法上-->
           <aop:aspect ref="myBook">
               <!--配置增强类型-->
               <aop:before method="before1" pointcut-ref="pointcut1">
           </aop:aspect>
       </aop:config>

</beans>

测试

package com.zhangjinbang.aop;
import org.junit.Test;
...

public class BookTest{
    @Test
    public void testAdd(){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        Book book=(Book)context.getBean("book");
        book.add();
    }
}

控制台输出内容

前置增强...
add book

上一篇 下一篇

猜你喜欢

热点阅读