知道美河 | 上传资料 | VIP申请 | 精品课程 | 资料搜索 | 问题反馈 | 会员手册 | 积分消费 | 积分充值 | 帐号保护
美河学习学习在线赞助VIP

美河学习在线(主站) eimhe.com

 找回密码
 建立账号
查看: 9596|回复: 1

[转帖] 在Spring2中使用引介

[复制链接]
发表于 2007-4-23 10:23:51 | 显示全部楼层 |阅读模式
引介(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>
发表于 2009-4-5 22:37:59 | 显示全部楼层
您需要登录后才可以回帖 登录 | 建立账号

本版积分规则

 
QQ在线咨询

QQ|小黑屋|手机版|Archiver|美河学习在线 ( 浙网备33020302000026号 )

GMT+8, 2025-5-2 06:51

Powered by Discuz!

© 2001-2025 eimhe.com.

快速回复 返回顶部 返回列表