對方法的加強叫對方法的加強叫作 Weaving(織入),而對類的加強叫作 Introduction(引入)。而 Introduction Advice(引入加強)就是對類的功能加強。spring
下面介紹一下引入增長。app
一個類沒有實現特定的接口,卻有該接口的功能。看AOP怎麼實現的ide
先定義一個接口測試
package advice.introduction; /** * Created by dingshuangkun on 2018/1/9. */ public interface Apology { void saySorry(String name); }
不讓GreetingImpl 實現該接口,但要讓GreetingImpl 擁有saySorry() 這個功能。代理
下面是GreetingImplxml
package aop.impl; import aop.Greeting; /** * Created by dingshuangkun on 2018/1/8. */ public class GreetingImpl implements Greeting { @Override public void sayHello(String name) { System.out.println("hello "+name); } @Override public void sayNiHao(String name) { System.out.println("niHao "+name); } }
沒有實現Apology這個接口。須要一個橋樑,把GreetingImpl 和Apology 關聯起來。藉助Spring 引入加強來實現接口
package advice.introduction; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.support.DelegatingIntroductionInterceptor; /** * Created by dingshuangkun on 2018/1/9. */ public class GreetingIntroAdvice extends DelegatingIntroductionInterceptor implements Apology { @Override public Object invoke(MethodInvocation mi) throws Throwable { return super.invoke(mi); } @Override public void saySorry(String name) { System.out.println("sorry "+name); } }
<bean id="greetingIntroAdvice" class="advice.introduction.GreetingIntroAdvice"/> <bean id="greetingProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="interfaces" value="advice.introduction.Apology"/> <!-- 須要動態實現的接口 --> <property name="target" ref="greetingImpl"/> <!-- 目標類 --> <property name="interceptorNames" value="greetingIntroAdvice"/> <!-- 引入加強 --> <property name="proxyTargetClass" value="true"/> <!-- 代理目標類(默認爲 false,代理接口) --> </bean>
測試get
public static void main(String[] arges){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Greeting greeting=(Greeting) ac.getBean("greetingProxy"); Apology apology = (Apology) greeting; apology.saySorry("ding"); }
結果io
sorry dingclass