标签:
public interface Waiter { void greetTo(String name); void serverTo(String name); }服务生实现类NativeWaiter.java
public class NativeWaiter implements Waiter{ public void greetTo(String name) { System.out.println("greet to"+name+"..."); } public void serverTo(String name) { System.out.println("serving"+name+"..."); } }服务生业务增强类GreetingBeforeAdvice.java
public class GreetingBeforeAdvice implements MethodBeforeAdvice{ /** * 前置增强方法 * 当该方法发生异常时,将阻止目标方法的执行 * @param method 目标类方法 * @param objects 目标类方法入参 * @param o 目标类对象实例 * @throws Throwable */ public void before(Method method, Object[] objects, Object o) throws Throwable { String clientName=(String)objects[0]; System.out.println("How Are You! mr."+clientName); } }
public class TestBeforeAdvice { public static void main(String[] args){ //创建目标对象 Waiter target=new NativeWaiter(); //创建增强类对象 BeforeAdvice advice=new GreetingBeforeAdvice(); //创建代理工厂对象 ProxyFactory factory=new ProxyFactory(); //设置代理类 factory.setTarget(target); //添加增强类 factory.addAdvice(advice); //获取代理类 Waiter proxy=(Waiter)factory.getProxy(); //调用目标类方法 proxy.greetTo("icarus"); proxy.serverTo("icarus"); } }
//创建代理工厂对象 ProxyFactory factory=new ProxyFactory(); //设置代理接口 factory.setInterfaces(target.getClass().getInterfaces()); //设置代理类 factory.setTarget(target); //设置增强类 factory.addAdvice(advice);
ProxyFactory factory=new ProxyFactory(); //设置代理接口 factory.setInterfaces(target.getClass().getInterfaces()); //启用cglib代理方式 factory.setOptimize(true); //设置代理类 factory.setTarget(target); //添加增强类 factory.addAdvice(advice);
<?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.xsd"> <bean id="gerrtingBefore" class="cn.lovepi.chapter07.aop.advice.GreetingBeforeAdvice"/> <bean id="target" class="cn.lovepi.chapter07.aop.advice.NativeWaiter"/> <bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean" p:proxyInterfaces="cn.lovepi.chapter07.aop.advice.Waiter" p:interceptorNames="gerrtingBefore" p:target-ref="target" /> </beans>
public class TestBeforeAdviceByXml { public static void main(String[] args){ String path="src/conf/conf-advice.xml"; ApplicationContext context=new FileSystemXmlApplicationContext(path); Waiter waiter=context.getBean("waiter",Waiter.class); waiter.greetTo("icarus"); waiter.serverTo("icarus"); } }
public class GreetingAfterAdvice implements AfterReturningAdvice{ /** * 后置增强代码实现 * @param o 代理返回对象 * @param method 目标对象方法 * @param objects 目标对象方法参数 * @param o1 目标对象 * @throws Throwable */ public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable { System.out.println("please enjoy youself!"); } }
<?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.xsd"> <bean id="gerrtingBefore" class="cn.lovepi.chapter07.aop.advice.GreetingBeforeAdvice"/> <bean id="gerrtingAfter" class="cn.lovepi.chapter07.aop.advice.GreetingAfterAdvice"/> <bean id="target" class="cn.lovepi.chapter07.aop.advice.NativeWaiter"/> <bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean" p:proxyInterfaces="cn.lovepi.chapter07.aop.advice.Waiter" p:interceptorNames="gerrtingBefore,gerrtingAfter" p:target-ref="target" /> </beans>
public class GreetingInterceptor implements MethodInterceptor{ /** * 业务逻辑实现类 * @param methodInvocation 封装了目标方法和入参数组以及目标方法所带的实例对象 * @return 代理对象 * @throws Throwable */ public Object invoke(MethodInvocation methodInvocation) throws Throwable { //获取目标方法的入参 Object[] args=methodInvocation.getArguments(); //获取方法名称 String clickName= (String) args[0]; System.out.println("GreetingInterceptor:How are you!"); //利用反射机制来调用目标方法 Object object=methodInvocation.proceed(); System.out.println("GreetingInterceptor: please enjoy youself!"); return object; } }
<?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.xsd"> <bean id="gerrtingBefore" class="cn.lovepi.chapter07.aop.advice.GreetingBeforeAdvice"/> <bean id="gerrtingAfter" class="cn.lovepi.chapter07.aop.advice.GreetingAfterAdvice"/> <bean id="gerrtingAround" class="cn.lovepi.chapter07.aop.advice.GreetingInterceptor"/> <bean id="target" class="cn.lovepi.chapter07.aop.advice.NativeWaiter"/> <bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean" p:proxyInterfaces="cn.lovepi.chapter07.aop.advice.Waiter" p:interceptorNames="gerrtingBefore,gerrtingAfter,gerrtingAround" p:target-ref="target" /> </beans>
public class ForumService { public void removeForum(){ //进行相应的数据库操作,但这里只为演示抛出异常 throw new RuntimeException("removeForum:Exception..."); } public void updateForum(){ //进行相应的数据库操作,但这里只为演示抛出异常 throw new RuntimeException("updateForum:Exception..."); } }
public class TransactionManager implements ThrowsAdvice{ /** * 捕获异常并打印异常名称 * @param method 目标对象对应方法 * @param args 方法入参 * @param target 目标对象 * @param ex 运行方法所捕获的异常 * @throws Throwable */ public void afterThrowing(Method method,Object[] args,Object target,Exception ex)throws Throwable{ System.out.println("method:"+method.getName()); System.out.println("抛出异常:"+ex.getMessage()); System.out.println("成功回滚事务"); } }
<?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.xsd"> <bean id="forumServiceTarget" class="cn.lovepi.chapter07.aop.advice.ForumService"/> <bean id="transactionManager" class="cn.lovepi.chapter07.aop.advice.TransactionManager"/> <bean id="forumService" class="org.springframework.aop.framework.ProxyFactoryBean" p:proxyTargetClass="true" p:target-ref="forumServiceTarget" p:interceptorNames="transactionManager" /> </beans>创建相应的测试类进行测试
public static void testThrowAdvice(){ String path="src/conf/conf-advice.xml"; ApplicationContext context=new FileSystemXmlApplicationContext(path); ForumService forumService=context.getBean("forumService",ForumService.class); try { forumService.removeForum(); }catch (Exception e){} try { forumService.updateForum(); }catch (Exception e){} }
public interface Monitorable { void setMonitorActive(boolean active); }创建测试接口Testable
public interface Testable { void test(); }接下来创建业务类
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(); } }
public class ControllablePerformaceMonitor extends DelegatingIntroductionInterceptor implements Monitorable, Testable { private ThreadLocal<Boolean> MonitorStatusMap = new ThreadLocal<Boolean>(); public void setMonitorActive(boolean active) { MonitorStatusMap.set(active); } public Object invoke(MethodInvocation mi) throws Throwable { Object obj = null; if (MonitorStatusMap.get() != null && MonitorStatusMap.get()) { PerformanceMonitor.begin(mi.getClass().getName() + "." + mi.getMethod().getName()); obj = super.invoke(mi); PerformanceMonitor.end(); } else { obj = super.invoke(mi); } return obj; } public void test() { // TODO Auto-generated method stub System.out.println("dd"); } }接下来创建所要增强的方法类
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); } } } public class MethodPerformace { private long begin; private long end; private String serviceMethod; public MethodPerformace(String serviceMethod){ reset(serviceMethod); } public void printPerformace(){ end = System.currentTimeMillis(); long elapse = end - begin; System.out.println(serviceMethod+"花费"+elapse+"毫秒。"); } public void reset(String serviceMethod){ this.serviceMethod = serviceMethod; this.begin = System.currentTimeMillis(); } }创建配置文件来将所设置的代码组合起来:
<?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="pmonitor" class="cn.lovepi.chapter07.aop.intorduce.ControllablePerformaceMonitor" /> <bean id="forumServiceTarget" class="cn.lovepi.chapter07.aop.intorduce.ForumService" /> <bean id="forumService" class="org.springframework.aop.framework.ProxyFactoryBean" p:interfaces="cn.lovepi.chapter07.aop.intorduce.Monitorable" p:target-ref="forumServiceTarget" p:interceptorNames="pmonitor" p:proxyTargetClass="true" /> </beans>创建对应的测试类
public class TestIntroduce { public static void main(String[] args) { testBeforeAdviceByCode(); } private static void testBeforeAdviceByCode() { String configPath = "src/conf/conf-advice-introduce.xml"; ApplicationContext ctx = new FileSystemXmlApplicationContext(configPath); ForumService forumService = (ForumService)ctx.getBean("forumService"); forumService.removeForum(10); forumService.removeTopic(1022); Monitorable moniterable = (Monitorable)forumService; moniterable.setMonitorActive(true); forumService.removeForum(10); forumService.removeTopic(1022); } }
标签:
原文地址:http://blog.csdn.net/icarus_wang/article/details/51737474