In this series of Groovy Quest Mop Nine interceptor, we have detailed the various aspects of a simple interceptor class, allowing us to initially have the basis of interceptors. This article needs to further implement our AOP programming with interceptor classes, based on the previous interceptor class.
First of all, in the first installment of this series, the methods we intercept are fixed. Now, we need to extend it to a user of the Interceptor class to specify the method to be intercepted.
First, give the class that needs to be intercepted:
class Foo {
def test1()
{
println 'test1'
}
def test2()
{
println 'test2'
}
def test3()
{
println 'test3'
}
}
And then give us the Interceptor class:
class MethodsInterceptor implements Interceptor{
def methods
Object beforeInvoke(Object object, String methodName, Object[] arguments){
if( methodName in this.methods )
{
println "before invoking $methodName"
}
null
}
boolean doInvoke(){ true }
Object afterInvoke(Object object, String methodName, Object[] arguments,
Object result){
if( methodName in this.methods )
{
println "after invoking $methodName"
}
result
}
}
With the foundation of the previous text, this interceptor class is better understood. The difference is that in the Interceptor class in the previous text, the method to intercept is fixed, and the method that the interceptor needs to intercept is determined by the attribute "methods".
Let's see how we use this interceptor class:
def proxy= ProxyMetaClass.getInstance( Foo )
proxy.interceptor= new MethodsInterceptor(methods:['test1','test2'])
proxy.use{
def f= new Foo()
f.test1()
f.test2()
f.test3()
}
The results of the operation are:
before invoking test1
test1
after invoking test1
before invoking test2
test2
after invoking test2
test3