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);
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!"); } }
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; } }
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("成功回滚事务"); } }
创建相应的测试类进行测试
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 ThreadLocalperformaceRecord = new ThreadLocal (); 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接下来创建所要增强的方法类MOnitorStatusMap= new ThreadLocal (); 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(); } }创建配置文件来将所设置的代码组合起来:
创建对应的测试类
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); } }
Spring学习(二十五)Spring AOP之增强介绍