使用Spring Introducation 让Java类实现动态语言特性
当我们没有一个实现类源代码以致不能为实现类增加新的方法时,我们在java语言中往往是无法实现的,但动态语言比(如JS),对动态对象增加可操作的方法是很容易得,我们借助Spring的Introduction这个特殊的advise,同样可以实现动态语言的这个特性
原始的业务接口及实现
package Introduction;
public interface ISome ...{
public void doSome();
}
package Introduction;
public class Some implements ISome ...{
public void doSome() ...{
System.out.println("原来的方法");
}
}
我们新增的业务接口和实现,其中实现类同时实现了业务接口和Spring Introduction接口
package Introduction;
public interface IOther ...{
public void doOther();
}
package Introduction;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.IntroductionInterceptor;
public class Other implements IOther, IntroductionInterceptor ...{
public void doOther() ...{
System.out.println("增加的职责");
}
public Object invoke(MethodInvocation methodInvocation) throws Throwable ...{
if(implementsInterface(methodInvocation.getMethod().getDeclaringClass()))...{
return methodInvocation.getMethod().invoke(this, methodInvocation.getArguments());
}else...{
return methodInvocation.proceed();
}
}
//判断是否来自与IOther接口的方法调用
public boolean implementsInterface(Class clazz) ...{
return clazz.isAssignableFrom(IOther.class);
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="some" class="org.springframework.aop.support.DefaultIntroductionAdvisor">
<constructor-arg ref="other"></constructor-arg>
<constructor-arg value="Introduction.IOther"></constructor-arg>
[img]http://b19.photo.store.qq.com/http_imgload.cgi?/rurl4_b=b319ad0568b952709699cf254a19161bed53f2f2894a