开发者

spring 3 AOP anotated advises

开发者 https://www.devze.com 2022-12-17 05:46 出处:网络
Trying to figure out how to Proxy my beans with AOP advices in annotated way. I have a simple class @Service

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!


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 {
        ...
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消