我们使用一个简单的例子来演示一下Spring中的AOP这是一个log的例子实际上log是一个对于AOP来说很不好的例子这里我们只为说明Spring AOP的使用
首先我们来创建一个自己的interceptor
这个类必须继承orgaopallianceintercept MethodInterceptor接口Spring的AOP框架就是参照aopalliance这个标准实现的所以我们的MyInterceptor要继承这个标准中的接口
这个接口只有一个要求实现的方法
public Object invoke(MethodInvocation methodInvocation) throws Throwable;
下面是我们的MyIntercptor
public class MyInterceptor implements MethodInterceptor {
private final Log logger = LogFactorygetLog(getClass());
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
(Beginning method (): +
methodInvocationgetMethod()getDeclaringClass() + +
methodInvocationgetMethod()getName() + ());
long startTime = SystemcurrentTimeMillis();
try{
Object result = methodInvocationproceed();
return result;
}finally{
(Ending method (): +
methodInvocationgetMethod()getDeclaringClass() + +
methodInvocationgetMethod()getName() + ());
(Method invocation time (): +
(SystemcurrentTimeMillis() startTime) + ms);
}
}
}
对于上面的代码需要说明的是下面两行代码
Object result = methodInvocationproceed();
return result;
整个程序的流程是这样的
先是执行在Object result = methodInvocationproceed();前面的代码
接着执行Object result = methodInvocationproceed();它把执行控制权交给了interceptor stack(拦截器栈)内的下一个interceptor如果没有了就交给真正的业务方法
然后执行return result;之前的代码
最后执行return result;它把控制权交回它之上的interceptor如果没有了就退出interceptor stack
写出我们的业务对象及其接口
为了方便我们的业务接口只有一个hello方法
public interface BusinessInterface {
public void hello();
}
业务对象的代码如下
public class BusinessInterfaceImpl implements BusinessInterface{
public void hello() {
Systemoutprintln(hello Spring AOP);
}
}
接下来我们来看看如何使用我们的写的interceptor
我们把业务对象作为AOP的target
<bean id=businessTarget class=comrstspringtestaopBusinessInterfaceImpl/>
接着在bean定义中声明interceptor
<bean id=myInterceptor class=comrstspringtestaopMyInterceptor/>
最后我们来声明真正的业务对象通过使用它的接口以及Spring的ProxyFactoryBean
<bean id=businessBean
class=orgspringframeworkaopframeworkProxyFactoryBean>
<property name=proxyInterfaces>
<value>comrstspringtestaopBusinessInterface</value>
</property>
<property name=interceptorNames>
<list>
<value>myInterceptor</value>
<value>businessTarget</value>
</list>
</property>
</bean>
这里需要说明两点
proxyInterfaces就是我们的业务对象的实际接口
interceptorNames定义了所有interceptors的执行顺序其中业务对象的target作为list的最后一个记着一定要把业务对象的target放到list中否则你的业务对象就不会工作
最后写我们的测试类
ClassPathResource resource =
new ClassPathResource(com/rst/spring/testaop/aop_beanxml);
XmlBeanFactory beanFactory = new XmlBeanFactory(resource);
BusinessInterface businessBean =
(BusinessInterface) beanFactorygetBean(businessBean);
businessBeanhello();
一切正常就可以在log上看到相应的信息了
以下是附件源代码的执行效果
:: INFO Beginning method (): interface comrstspringtestaopBusinessInterfacehello()
:: INFO Beginning method (): interface comrstspringtestaopBusinessInterfacehello()
hello Spring AOP
:: INFO Ending method (): interface comrstspringtestaopBusinessInterfacehello()
:: INFO Ending method (): interface comrstspringtestaopBusinessInterfacehello()
:: INFO Method invocation time (): ms
源代码需要springjar aopalliencejar commonsloggingjar