Groovy Quest Mop 10 Interceptor II

Source: Internet
Author: User
Tags object object

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.