SpringAOP之引介增強 IntroductionInterceptor

SpringAOP常見的有前置、後置、環繞、異常處理等技術,今天介紹AOP中的引介增強。這個技術是類級別的。


定義Monitor


package com.augmentum.introductionInterceptor;

public interface Monitor {
	void setMonitorActive(boolean bool);
}


實現類繼承了 IntroductionInterceptor


package com.augmentum.introductionInterceptor;

public class PerformanceMonitor {
	private static ThreadLocal<MethodPerformace> performaceRecord = new ThreadLocal<MethodPerformace>();
	public static void begin(String method) {
		System.out.println("begin monitor...");
		MethodPerformace mp = performaceRecord.get();
		if(mp == null){
			mp = new MethodPerformace(method);
			performaceRecord.set(mp);
		}else{
		    mp.reset(method);	
		}
	}
	public static void end() {
		System.out.println("end monitor...");
		MethodPerformace mp = performaceRecord.get();
		mp.printPerformace();
	}
}



業務類


package com.augmentum.introductionInterceptor;

public class ForumService {

	public void removeTopic(int topicId) {
		System.out.println("模擬刪除Topic記錄:"+topicId);
		try {
			Thread.currentThread().sleep(20);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}		

	}

	public void removeForum(int forumId) {
		System.out.println("模擬刪除Forum記錄:"+forumId);
		try {
			Thread.currentThread().sleep(40);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}		
	}
}


測試類


package com.augmentum.introductionInterceptor;

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

public class TestIntroduce {
	public static void main(String[] args) {
		String path = "conf/conf-advice-introduce.xml";
		ApplicationContext ac = new ClassPathXmlApplicationContext(path);
		ForumService forumService = (ForumService) ac.getBean("forumService");
		forumService.removeForum(100);
		
		Monitor monitor = (Monitor)forumService;
		monitor.setMonitorActive(true);
		
		forumService.removeForum(100);
		forumService.removeTopic(1000);
	}
}


配置文件


<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="monitor" class="com.augmentum.introductionInterceptor.ControMonitor"/>
	<bean id="target" class="com.augmentum.introductionInterceptor.ForumService"/>
	
	<bean id="forumService" class="org.springframework.aop.framework.ProxyFactoryBean"
		p:interfaces="com.augmentum.introductionInterceptor.Monitor" 
		p:target-ref="target"
		p:interceptorNames="monitor" p:proxyTargetClass="true" />
</beans>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章