天天看点

Spring AOP-通知-后置通知AOP-通知-后置通知

AOP-通知-后置通知

工程用到的jar包:http://pan.baidu.com/s/1dFFw6at

接口

package com.hk.spring.aop02;

public interface SomeService {

    public void doFirst();
    public void doSecond();
}
           

接口实现

package com.hk.spring.aop02;

public class SomeServiceImpl implements SomeService {

    @Override
    public void doFirst() {

        System.out.println("主业务doFirst");
    }

    @Override
    public void doSecond() {

        System.out.println("主业务doSecond");
    }

}
           

后置通知类

package com.hk.spring.aop02;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

/**
 *  前置通知
 * @author 浪丶荡
 *
 */
public class MyAfterReturningAdvice implements AfterReturningAdvice {

    //在目标方法执行之后执行
    @Override
    public void afterReturning(Object returnValue, Method method,
            Object[] args, Object target) throws Throwable {
        System.out.println("后置通知执行");
    }


}
           

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean name = "someService" class="com.hk.spring.aop02.SomeServiceImpl"></bean>
    <!-- 注册通知 -->
    <bean name = "myAfterReturningAdvice" class="com.hk.spring.aop02.MyAfterReturningAdvice"></bean>
    <!-- 生成代理对象 -->
    <bean name = "serviceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    <!-- 配置代理对象的目标对象属性 (类加载器)-->
    <property name="target" ref="someService"/>
    <!-- 或者这样配置
    <property name="targetName" value="someService"/>
    -->
    <!-- 配置切面 (方法)-->
    <property name="interceptorNames" value="myAfterReturningAdvice"/>
    <!-- 接口通过private boolean autodetectInterfaces = true可以被找到 -->
    </bean>

</beans>
           

测试

package com.hk.spring.aop02;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {

    @Test
    public void test1(){
        String resoure = "com/hk/spring/aop02/applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(resoure);
        SomeService someService = (SomeService) ac.getBean("serviceProxy");
        someService.doFirst();
        someService.doSecond();
    }
}
           

结果

主业务doFirst
后置通知执行
主业务doSecond
后置通知执行
           

与前置通知的唯一区别就是实现的接口不同

继续阅读