1. 程式人生 > >AOP前置通知

AOP前置通知

<?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.aop01.SomeServiceImpl"/>
	
		<!-- 註冊切面:通知 -->
		<bean id="myAdvice" class="com.gqc.aop01.MyMethodBeforeAdvice"/>
		
		<!-- 生成代理物件 -->
		<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>
package com.gqc.aop01;

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



public class MyTest {

		@Test
		public void test01() {
			//建立容器物件 載入Spring 配置檔案
			String resource = "com/gqc/aop01/appliactionContext.xml";
			ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
			ISomeService service=(ISomeService)ac.getBean("serviceProxy");
			service.doFirst();
			System.out.println("-----------------");
			service.doSecond();
		}
		
}

package com.gqc.aop01;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

//前置通知
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
	//當前方法在目標方法執行之前執行
	//method:目標方法
	//args:目標方法的 引數列表
	//target:目標物件
	@Override
	public void before(Method method, Object[] args, Object target)
			throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("執行前置通知方法");
		
	}



}