1

注釈付きの方法で AOP アドバイスを使用して豆をプロキシする方法を見つけようとしています。

私は簡単なクラスを持っています

@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構成なしでそれを行うことはできますか?

インターセプトしたいメソッドに注釈を付けるだけでよいと思います.Spring DIは必要なものをプロキシします。

または、そのためにaspectjを使用する必要がありますか? 最も簡単な解決策を好むでしょう:-)

助けてくれてどうもありがとう!

4

1 に答える 1

3

AspectJを使用する必要はありませんが、SpringでAspectJアノテーションを使用できます(7.2 @AspectJサポートを参照)。

@Aspect
public class AroundExample {
    @Around("@annotation(...)")
    public Object invoke(ProceedingJoinPoint pjp) throws Throwable {
        ...
    }
}
于 2010-01-18T17:11:57.057 に答える