AOP 那些事三

SpringAOP实践
本文介绍了一个具体的Spring AOP(面向切面编程)应用实例。通过定义`GreetingAroundAdvice`类实现了方法拦截器,该类在目标方法调用前后分别执行自定义的前置和后置操作。使用Spring框架配置了代理工厂Bean来创建代理对象,并在主方法中演示了如何通过应用程序上下文获取并调用代理对象的方法。

在spring实现

import org.aopalliance.intercept.MethodInvocation;

/**
 * Created by dingshuangkun on 2018/1/9.
 */
public class GreetingAroundAdvice implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        before();
        Object obj =  invocation.proceed();
        after();
        return obj;
    }

    public void before(){
        System.out.println("----before----");
    }
    public void after(){
        System.out.println("----after------");
    }
}
<bean id="greetingImpl" class="aop.impl.GreetingImpl"/>
<bean id="greetingAroundAdvice" class="aop.GreetingAroundAdvice"/>
<bean id="greetingProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="interfaces" value="aop.Greeting"/>
    <property name="target" ref="greetingImpl"/>
    <property name="interceptorNames" >
        <list>
            <value>greetingAroundAdvice</value>
        </list>
    </property>
</bean>

测试

public static void main(String[] arges){
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    Greeting greeting =(Greeting) ac.getBean("greetingProxy");
    greeting.sayHello("ding");
    greeting.sayNiHao("dingding");
}

------before-------
hello ding
------after--------
------before-------
niHao dingding
------after--------

转载于:https://my.oschina.net/u/3218528/blog/1604609

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值