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>