aop 之 helloworld

 先看看xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>      

<bean id="MyInterceptor" class="MethodTimeCostInterceptor"/>             

<bean id="myAOPProxy"  class="org.springframework.aop.framework.ProxyFactoryBean">             
 <property name="proxyInterfaces">
  <value>ITest</value>             
 </property>                           
 <property name="target">                    
  <ref local="test"/>             
 </property>             
 <property name="interceptorNames">                    
  <value>MyInterceptor</value>             
 </property>       
</bean>      

<bean id="test" class="Test">      
</bean>

</beans>

2:然后我们添加一个接口:ITest。内容如下:
public interface ITest {
  public  void select() throws Exception;
  public  void update();
  public  void delete();
}

3:添加实现类:Test。实现如下:
public class Test
    implements ITest {
  long a = 10;
  public void select() throws Exception {
    for (int i = 0; i < 25; i++) {
      a =a + a;
    }
    System.out.println("the value si ............. " +a);
  }

  public void update() {
    System.out.println("update......................");
  }

  public void delete() {
    System.out.println("delete......................");
  }

}

4:最后是Interceptor:
public class MethodTimeCostInterceptor
    implements MethodInterceptor, Serializable {
 
  public Object invoke(MethodInvocation invocation) throws Throwable {
    System.out.println("the invocation's name is ..... " + invocation.getMethod().getName());
    long time = System.currentTimeMillis();
    System.out.println("begin");
    Object rval = invocation.proceed();
       
    System.out.println("the invocation's params is ....... "+invocation.getMethod().getParameterTypes());
    time = System.currentTimeMillis() - time;
    System.out.println("end");
    System.out.println("the time is ..... "+time);
    return rval;
  }
}
5:测试main方法:
public static void main(String ar[]){
   
    ClassPathResource resource = new ClassPathResource("beans.xml");
    XmlBeanFactory beanFactory = new XmlBeanFactory(resource);
    ITest itest =(ITest) beanFactory.getBean("myAOPProxy");
    try {
      itest.select();
    }
    catch (Exception ex) {
    }
  }

我们看到了所有的源码。配置spring 这里就不多说了,运行main方法就可以看到执行之后的结果。此文只是起到抛砖引玉的目的,有什么错误的地方请指出,谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值