1. 程式人生 > >Spring AOP-通知-為目標方法織入多個切面

Spring AOP-通知-為目標方法織入多個切面

AOP-通知-為目標方法織入多個切面

開發中可能會遇到為目標方法織入多個切面,比如前置。後置通知都需要

介面

package com.hk.spring.aop06;

public interface SomeService {

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

介面實現

package com.hk.spring.aop06;

public class SomeServiceImpl implements SomeService {

    @Override
    public void
doFirst() { System.out.println("主業務doFirst"); } @Override public void doSecond() { System.out.println("主業務doSecond"); } }

前置通知

kpackage com.hk.spring.aop06;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

/**
* 前置通知
* @author 浪丶蕩
*
*/
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

//在目標方法執行之前執行
@Override
public void before(Method method, Object[] args, Object target)
        throws Throwable {
    System.out.println("前置通知執行");
}

}

後置通知

package com.hk.spring.aop06;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

/**
 *  後置通知
 * @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.aop06.SomeServiceImpl"></bean>
    <!-- 註冊前置通知 -->
    <bean name = "myMethodBeforeAdvice" class="com.hk.spring.aop06.MyMethodBeforeAdvice"></bean>
    <!-- 註冊後置通知 -->
    <bean name = "myAfterReturningAdvice" class="com.hk.spring.aop06.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="myMethodBeforeAdvice,myAfterReturningAdvice"/>
    <!-- 介面通過private boolean autodetectInterfaces = true可以被找到 -->
    </bean>

</beans>

測試

package com.hk.spring.aop06;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hk.spring.aop06.SomeService;
public class Mytest {

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

結果

前置通知執行
主業務doFirst
後置通知執行
前置通知執行
主業務doSecond
後置通知執行