Spring 使用介绍(五)—— AOP

一、简单使用:Hello World实例

1、定义目标类

public interface Hello {
    void sayHello();
}
public class HelloImpl implements Hello {
    @Override
    public void sayHello() {
        System.out.println("hello matt!");
    }
}

2、定义切面支持类

public class HelloAspect {
    public void beforeAdvice() {
        System.out.println("****beforeAdvice");
    }

    public void afterFinnallyAdvice() {
        System.out.println("****afterFinnallyAdvice");
    }
}

3、配置切面

<?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-3.0.xsd
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">  
    
    <!-- 目标类 --> 
    <bean id="hello" class="cn.matt.aop.HelloImpl"></bean>
    
    <!-- 切面支持类 --> 
    <bean id="helloAspect" class="cn.matt.aop.HelloAspect"></bean>

    <aop:config>  
        <!-- 切点 --> 
        <aop:pointcut id="pointcut" expression="execution(* cn.matt.aop..*.*(..))"/>  
        <!-- 切面 -->
        <aop:aspect ref="helloAspect">  
            <aop:before pointcut-ref="pointcut" method="beforeAdvice"/>  
            <aop:after pointcut="execution(* cn.matt.aop..*.*(..))" method="afterFinnallyAdvice"/>  
        </aop:aspect>  
    </aop:config>  
</beans>

4、测试

@Test
public void testSayHello() {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
    Hello hello = context.getBean(Hello.class);
    hello.sayHello();
}

输出:

****beforeAdvice
hello matt!
****afterFinnallyAdvice

二、AOP配置介绍

AOP相关定义必须放在<aop:config>标签下,该标签下可以有<aop:pointcut>、<aop:advisor>、<aop:aspect>标签,配置顺序不可变

AOP配置步骤:

1)声明切面支持bean(通过<bean>标签实例化支持类)

2)声明切面,引用切面支持bean(切面由<aop:aspect>标签指定,ref属性用来引用切面支持Bean)

3)声明切入点,有两种方式,注意切入点也是bean

  i)使用<aop:pointcut>声明一个切入点Bean,该切入点可被多个切面共享

<aop:config>  
  <aop:pointcut id="pointcut" expression="execution(* cn.javass..*.*(..))"/>  
  <aop:aspect ref="aspectSupportBean">  
     <aop:before pointcut-ref="pointcut" method="before"/>  
  </aop:aspect>  
</aop:config>

  ii)匿名切入点Bean,通过pointcut属性指定

<aop:config>  
  <aop:aspect ref="aspectSupportBean">  
      <aop:after pointcut="execution(* cn.javass..*.*(..))" method="afterFinallyAdvice"/>  
   </aop:aspect>  
</aop:config> 

4)声明通知,有五种:

  i)前置通知  方法调用前调用

  ii)后置返回通知  方法调用后且正常返回时调用

  iii)后置异常通知  方法调用后且抛出异常时调用

  iv)后置最终通知  方法调用后始终调用

  v)环绕通知  可控制方法的执行过程,如决定方法是否执行,什么时候执行,执行时替换方法参数,执行后替换返回值等

  

猜你喜欢

转载自www.cnblogs.com/MattCheng/p/8926732.html