1. 程式人生 > >AOP 環繞通知

AOP 環繞通知

package com.gqc.aop03;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

//環繞通知可以修改目標方法的返回結果
public class MyMethodInterceptor implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		System.out.println("執行環繞通知:目標方法執行之前");
		//執行目標方法
		Object result = invocation.proceed();
		System.out.println("執行環繞通知:目標方法執行之後");
		if(result!=null){
			result=((String)result).toUpperCase();
		}
		return result ;
	}

}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd">

		<!-- 註冊目標物件 -->
		<bean id="someService" class="com.gqc.aop03.SomeServiceImpl"/>
	
		<!-- 註冊切面:後置通知 -->
		<bean id="myAdvice" class="com.gqc.aop03.MyMethodInterceptor"/>
		
		<!-- 生成代理物件 -->
		<bean id="serviceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
			<!-- 指定目標物件 -->
			<property name="target" ref="someService"/>
			<!-- <property name="targetName" value="someService"/> -->
			<!-- 指定切面 -->
			<property name="interceptorNames" value="myAdvice"/>
		</bean>
				
</beans>