spring 3 AOP anotated advises

Posted by Art79 on Stack Overflow See other posts from Stack Overflow or by Art79
Published on 2010-01-18T17:02:58Z Indexed on 2010/03/24 23:03 UTC
Read the original article Hit count: 609

Filed under:
|
|

Trying to figure out how to Proxy my beans with AOP advices in annotated way.

I have a simple class

@Service
public class RestSampleDao {

    @MonitorTimer
    public Collection<User> getUsers(){
                ....
        return users;
    }
}

i have created custom annotation for monitoring execution time

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface MonitorTimer {
}

and advise to do some fake monitoring

public class MonitorTimerAdvice implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable{
        try {
            long start = System.currentTimeMillis();
            Object retVal = invocation.proceed();
            long end = System.currentTimeMillis();
            long differenceMs = end - start;
            System.out.println("\ncall took " + differenceMs + " ms ");
            return retVal;
        } catch(Throwable t){
            System.out.println("\nerror occured");
            throw t;
        }
    }
}

now i can use it if i manually proxy the instance of dao like this

    AnnotationMatchingPointcut pc = new AnnotationMatchingPointcut(null, MonitorTimer.class);
    Advisor advisor = new DefaultPointcutAdvisor(pc, new MonitorTimerAdvice());

    ProxyFactory pf = new ProxyFactory();
    pf.setTarget( sampleDao );
    pf.addAdvisor(advisor);

    RestSampleDao proxy = (RestSampleDao) pf.getProxy();
    mv.addObject( proxy.getUsers() );

but how do i set it up in Spring so that my custom annotated methods would get proxied by this interceptor automatically? i would like to inject proxied samepleDao instead of real one. Can that be done without xml configurations?

i think should be possible to just annotate methods i want to intercept and spring DI would proxy what is necessary.

or do i have to use aspectj for that? would prefere simplest solution :- )

thanks a lot for help!

© Stack Overflow or respective owner

Related posts about spring-framework

Related posts about aop