引入是为需要方法的类添加属性和方法。可以用一个已存在的类让他实现另外的接口,维持另外的状态(这也叫混合)。引入能够动态的建立复合对象,提供了多态继承的好处。
class AuditableIntroductionInterceptor extends DelegatingIntroductionInceptor{
private Date lastModifiedDate ;
public Date getLastModifiedDate(){}
public void setLastModifiedDate(Date date){}
}
如果你的混合体要改变任何目标对象方法的行为的话,你就需要实现invoke()方法。
public Object invoke(MethodInvcation mi) throws Throwable{
String name = mi.getMethod().getName();
if(name.indexof("set") == 0){
throw new IllegalModificationException();
}
return super.invoke(mi);
}
我们复写了invoke方法,所以他拦截所有的方法的调用。注意我们调用的super.invoke()而
不是mi.proceed().这样做是因为父类DelegatingIntroductionInterceptorkeyijiang可以
决定哪个类负责处理这个方法调用。这一点需要注意,当需要复写invoke方法时,你需要调用
super.invoke方法来确保调用正确的方法。
public class MyDDI extends DelegatingIntroductionInterceptor implements
ModifyData {
private static final long serialVersionUID = 8244858324942778490L;
private String data;
public void setData(String data) {
this.data = data;
}
public String getData() {
return this.data;
}
}
public interface ModifyData {
public void setData(String data);
public String getData();
}
<bean id="myDII" class="study.spring.aop.advice.MyDDI"></bean>
<!-- 默认的引入切入点通知(代理引入拦截器,对引入通知进行包装) -->
<bean id="delegatingIntroductionInterceptor" class="org.springframework.aop.support.DelegatingIntroductionInterceptor">
<constructor-arg ref="myDII"></constructor-arg>
</bean>
<!-- 目标对象 -->
<bean id="welcomeServiceTarget" class="study.spring.aop.WelcomeServiceImpl"></bean>
<!-- 对象代理 -->
<bean id="welcomeService" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 代理接口集 -->
<property name="proxyInterfaces">
<list>
<value>study.spring.aop.ModifyData</value>
</list>
</property>
<!-- 拦截器名集 -->
<property name="interceptorNames">
<list>
<!-- <value>myMethodInterceptor</value> -->
<value>delegatingIntroductionInterceptor</value>
</list>
</property>
<!-- 指定目标对象 -->
<property name="target" ref="welcomeServiceTarget"></property>
</bean>
ApplicationContext ac = new ClassPathXmlApplicationContext("study/spring/aop/dii.xml");
WelcomeService ws = (WelcomeService)ac.getBean("welcomeService");
ModifyData md = (ModifyData)ws;
md.setData("data");
System.out.println(md.getData());