views:

193

answers:

1

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!

+2  A: 

You haven't to use AspectJ, but you can use AspectJ annotations with Spring (see 7.2 @AspectJ support):

@Aspect
public class AroundExample {
    @Around("@annotation(...)")
    public Object invoke(ProceedingJoinPoint pjp) throws Throwable {
        ...
    }
}
axtavt
thanks that solved the problem :- )
Art79