春季3 AOP注释建议

时间:2010-01-18 17:02:58

标签: aop spring aspectj

试图找出如何以注释方式使用AOP建议代理我的bean。

我有一个简单的课程

@Service
public class RestSampleDao {

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

我已经创建了用于监控执行时间的自定义注释

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

并建议做一些假监控

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;
        }
    }
}

现在我可以使用它,如果我像这样手动代理dao的实例

    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() );

但是我如何在Spring中设置它以便我的自定义注释方法会被这个拦截器自动代理?我想注入代理的samepleDao而不是真正的。可以在没有xml配置的情况下完成吗?

我认为应该可以只注释我想拦截的方法,而春天的DI会代替必要的。

或者我必须使用aspectj吗?会选择最简单的解决方案: - )

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:3)

您不必使用AspectJ,但可以在Spring中使用AspectJ注释(请参阅7.2 @AspectJ support):

@Aspect
public class AroundExample {
    @Around("@annotation(...)")
    public Object invoke(ProceedingJoinPoint pjp) throws Throwable {
        ...
    }
}
相关问题