Spring AOP深入剖析
副标题[/!--empirenews.page--]
一、通过代理工厂模式配置通知 ①、前置通知、后置通知: 定义某接口:ISomeService,并自定义方法 public interface ISomeService { public void tran() throws Exception; public void log(); } 定义类 实现该接口,并重写方法: public class SomeService implements ISomeService{ public void tran() throws Exception{ System.out.println("开启事务!!"); } public void log() { System.out.println("记录日志!!"); } 定义前置通知类,并实现MethodBeforeAdvice该接口 public class MyBefore implements MethodBeforeAdvice{ public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("==before=="); } 定义后置通知类,并实现AfterReturningAdvice该接口 public class MyAfter implements AfterReturningAdvice{ public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("==after=="); } 配置Spring配置文件applicationContext.xml: 代理工厂:ProxyFactoryBean 测试类: 实现效果: ② 环绕通知 MethodInterceptor 环绕增强在目标方法的前后都可以织入增强处理。环绕增强是功能最强大的强大处理。Spring把目标方法的控制权全部交给了他。在环绕增强处理中,可以获取或修改目标方法的参数、返回值、可以对它进行异常处理,甚至可以决定目标方法是否执行。 配置Spring文件: <!-- 环绕增强 --> <bean id="some" class="cn.happy.entity.SomeService"></bean> <bean id="arround" class="cn.happy.arround.MyInterceptor"></bean> <bean id="factory" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="some"></property> <property name="interceptorNames" value="arround"></property> </bean> 实现效果: 通过MethodInterceptor接口实现了环绕增强。该接口要求实现invoke()方法,其参数MethodInvocation不但封装目标方法及其参数组,还封装了被代理目标对象。通过proceed()方法可以调用目标对象的相应方法,从而实现对目标方法的完全控制! ③异常通知: 特点是在目标方法抛出异常时织入增强处理。通过ThrowsAdvice接口实现异常抛出增强,但ThrowsAdvice接口中并没有定义任何方法,但是我们在定义异常抛出的增强方法时必须遵守以下方法签名: void afterThrowing([Method method,Object[]arguments,Object target,] Throwable ex) 实现类出现异常情况下: Spring配置文件: <!-- 异常通知 --> <bean id="some" class="cn.happy.entity.SomeService"></bean> <bean id="throws" class="cn.happy.throwsAdvice.MyThrows"></bean> <bean id="factory" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="some"></property> <property name="interceptorNames" value="throws"></property> </bean> 测试类: 若将异常抛给上级处理,则在控制台通过,单测报错,若将异常手动抛出,则相反 @Test public void proxyTest(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); ISomeService ser=(ISomeService) ctx.getBean("factory"); //ser.tran(); try { ser.tran(); } catch (Exception e) { e.printStackTrace(); } ser.log(); }
二、顾问Advisor 顾问Advisor是Spring提供的另一种切面。其可以完成更为复杂的切面织入功能。PointcutAdvisor是顾问的一种,可以指定具体的切入点。顾问将通知进行了包装,会根据不同的通知类型,在不同的时间点,将切面织入到不同的切入点。 如何实现: 同理:定义接口和实现类,并自定义方法。以及前置增强的类。关键点在Spring配置文件 ①名称匹配方法切入点顾问 ② 正则表达式匹配方法切入点顾问 三、自动代理生成器 注意:默认Advisor自动代理生成器,切面只能是顾问,对所有的对象都增强 两种实现方式: ① 默认Advisor自动代理生成器 DefaultAdvisorAutoProxyCreator ② BeanName自动代理生成器 BeanNameAutoProxyCreator 在这里 无需配置代理工厂bean,测试类getBean()取的id是配置文件的被代理对象 切面只能是顾问的情况下: 实现效果: 既可以是通知也可以是顾问的情况下:
实现效果: (编辑:应用网_丽江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |