Introduction(引入)是个特别的Advice,类通过实现AOP中的org.springframework.aop.IntroductionInterceptor在不改变原有方法的基础上却可以增加新的方法。IntroductionInterceptor继承了MethodInterceptor和DynamicIntroductionAdvic
示例:需要导入aopalliance-1.0.jar和spring-aop-2.5.1.jar
目标接口:
package com.yourcompany.spring;
public interface ISome {
public void doSome();
}
目标实现:
package com.yourcompany.spring;
public class Some implements ISome{
public void doSome(){
System.out.println("原来Some对象的功能...");
}
}
新增接口:
package com.yourcompany.spring;
public interface IOther{
public void doOther();
}
新增实现:
package com.yourcompany.spring;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.IntroductionInterceptor;
public class Other implements IntroductionInterceptor,IOther{
public void doOther(){
System.out.println("Other对象的功能");
}
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
if(implementsInterface(methodInvocation.getMethod().getDeclaringClass())){
return methodInvocation.getMethod().invoke(this, methodInvocation.getArguments());
}
else{
return methodInvocation.proceed();
}
}
public boolean implementsInterface(Class arg0){
boolean assignableFrom = arg0.isAssignableFrom(IOther.class);
return assignableFrom;
}
}
applicationContext.xml:
<?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.5.xsd">
<bean id="some" class="com.yourcompany.spring.Some" />
<bean id="other" class="com.yourcompany.spring.Other" />
<bean id="otherAdvisor" class="org.springframework.aop.support.DefaultIntroductionAdvisor">
<constructor-arg ref="other"></constructor-arg>
<constructor-arg value="com.yourcompany.spring.IOther" />
</bean>
<bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces" value="com.yourcompany.spring.ISome" />
<property name="target" ref="some" />
<property name="interceptorNames">
<list>
<value>otherAdvisor</value>
</list>
</property>
</bean>
</beans>
程序主入口:
package com.yourcompany.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Introduction{
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
ISome some=(ISome)context.getBean("proxyFactoryBean");
some.doSome();
((IOther)some).doOther();
}
}
另:Spring框架中的类DelegatingIntroductionInterceptor是接口DelegatingIntroductionInterceptor的默认实现类,用法大致相同。