今天基本上把《深入Spring2:轻量级J2EE开发框架原理与实践》中的AOP一章的最后的示例程序理清了,将会在这两天整理好后发出来。实在太困了,清理一下头绪,这里随便写一点关于Spring2中最简单的引介Introduction使用方法! 引介(Introduction)是指在不更改源代码的情况,给一个现有类增加属性、方法,以及让现有类实现其它接口或指定其它父类等,从而改变类的静态结构。Spring AOP通过采代理加拦截器的方式来实现的,可以通过拦截器机制使一个实有类实现指定的接口,由于是使用拦截器的机制,因此Spring AOP中引介的底层仍然是通知(Advice)及拦截(Interceptor)。Spring2引入了对AspectJ5的切入点表达式解析引擎,因此,对于一些普通的AOP切面模块功能,可以像AspectJ一样来使用AOP。本文简单演示Spring2中引介的使用! 假如有一个类demo.HeroImpl,现在我们要在系统中增加一个SmartHero接口,现在需要在不改变demo.HeroImpl的代码的情况下,让HeroImpl对象实现SmartHero接口。 SmartHero接口的内容如下: public interface SmartHero{ void doSmartExit(); } 有一个SmartHero的实现SmartHeroImpl,内容如下: public class SmartHeroImpl implements SmartHero { public void doSmartExit() { System.out.println("I'm smart exit!"); } } 现在要让demo.HeroImpl实现SmarHero接口,可以通过下面的方式: 1、定义一个切面 import org.aspectj.lang.annotation.DeclareParents; import org.aspectj.lang.annotation.Aspect; public class AspectIntro { @DeclareParents(value="demo.HeroImpl",defaultImpl=SSmartHeroImpl.class) private SmartHero smart; } 2、在配置文件中使用使用<aop:aspectj-autoproxy/>来开始@AspectJ自动代理。 3、声明一个切面Bean。 <!--使用普通Bean方式定义一个切面模块--> <bean id="aspectIntro" class="demo.AspectIntro"/> <bean id="hero" class="demo.HeroImpl"/> 4、所有由Spring容器管理的HeroImpl对象都将会自实现了SmartHero接口。在客户端可以这样来使用: HeroImpl hero=(HeroImpl)factory.getBean("hero"); SmartHero hero=(SmarHero)hero;
当然,Spring2中也支持老版本AOP API中的ProxyFactoryBean来定义引介。要实现上面的功能,可以使用大致如下的方法: 1、定义一个IntroductionAdvisor(引介器),直接继承DefaultIntroductionAdviso来得到! import org.springframework.aop.support.DefaultIntroductionAdvisor; import org.springframework.aop.support.DelegatingIntroductionInterceptor; public class SmartHeroIntroductionAdvisor extends DefaultIntroductionAdvisor { public SmartHeroIntroductionAdvisor() { super(new DelegatingIntroductionInterceptor(new SmartHeroImpl()), SuperHero.class); } }
2、在Spring配置文件配置一个IntroductionAdvisor。如下: <bean id="superHeroIntroduction" class="demo.SuperHeroIntroductionAdvisor" /> 3、使用代理ProxyFactoryBean来定义Hero,如下: <bean id="hero" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target"><bean class="demo.HeroImpl"/> </property> <property name="interceptorNames"> <list> <value>superHeroIntroduction</value> </list> </property> </bean>
更多关于Spring2中AOP的详细信息,请参考《深入Spring 2:轻量级J2EE开发框架原理与实践》电子版!
|
|