<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方法就可以看到执行之后的结果。此文只是起到抛砖引玉的目的,有什么错误的地方请指出,谢谢。