JavaWeb学习笔记-spring-09-AOP-创建增强类(前置增强)

创建增强类

增强类型

  • 增强类型
    • 前置增强Before
    • 后置增强AfterReturningAdvice
    • 环绕增强MethodInterceptor
    • 异常抛出增强ThrowsAdvice
    • 引介增强IntroductionInterceptor
前置增强
public interface Waiter {
    void greetTo(String name);
    void serveTo(String name);
}
public class NativeWaiter implements Waiter {
    public void greetTo(String name) {
        System.out.println("greet to "+name+"...");
    }

    public void serveTo(String name) {
        System.out.println("serving " + name + "...");
    }
}
public class GreetingBeforeAdvice implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        String clientName = (String)objects[0];
        System.out.println("How are you!Mr."+ clientName+".");
    }
}
public class BeforeAdviceTest {
    private Waiter target;
    private BeforeAdvice advice;
    private ProxyFactory pf;
    @Before
    public void init(){
        target = new NativeWaiter();
        advice = new GreetingBeforeAdvice();
        //spring提供代理工厂
        pf = new ProxyFactory();
        //设置代理目标
        pf.setTarget(target);
        //为代理目标设置增强
        pf.addAdvice(advice);
    }
    @Test
    public void beforeAdvice(){
        Waiter proxy = (Waiter)pf.getProxy();
        proxy.greetTo("John");
        proxy.serveTo("Tom");
    }
}
在spring中配置
    <bean id="greetingAdvice" class="com.smart.advice.GreetingBeforeAdvice"/>
    <bean id="target" class="com.smart.advice.NativeWaiter"/>
    <!-- proxyInterfaces指定代理接口,如果是多个接口,使用<list>元素-->
    <!-- interceptorNames指定使用的增强-->
    <!-- target-ref指定对哪个进行代理-->
    <bean id="waiter" class="org.springframework.aop.framework.ProxyFactoryBean"
          p:proxyInterfaces="com.smart.advice.Waiter"
          p:interceptorNames="greetingAdvice"
          p:target-ref="target"/>
  • ProxyFactoryBean
    • proxyInterfaces:代理所要实现的接口
    • interceptorName:需要植入目标对象的Bean列表
    • singleton:返回代理是否是单实例
    • optimize:设置为true时,强制使用CGLIB代理
    • proxyTargetClass:是否对类进行代理(而不是对接口),为true使用CGLIB代理
public class SpringAdviceTest {
    @Test
    public void testAdvice(){
        String configPath = "beans.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
        Waiter waiter = (Waiter)ctx.getBean("waiter");
        waiter.greetTo("John");
    }
}
    <!-- 使用CGLib代理,将proxyTargetClass设置为true-->
    <!-- 无需设置proxyInterfaces属性-->
    <bean id="waiter1" class="org.springframework.aop.framework.ProxyFactoryBean"
          p:interceptorNames="greetingAdvice"
          p:target-ref="target"
          p:proxyTargetClass="true"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值