AOP 那些事(四)

对方法的加强叫对方法的加强叫作 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

相关文章
相关标签/搜索