質問
注釈付きの方法で 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の代わりにプロキシされたsamepleDaoを注入したいと考えています。XML設定なしでそれを行うことはできますか?
インターセプトしたいメソッドに注釈を付けるだけでよいと思います。Spring DIは必要なものをプロキシします。
それともそのためにaspectjを使用する必要がありますか?最も単純な解決策を好むでしょう:-)
助けてくれて本当にありがとう!
解決
AspectJ を使用する必要はありませんが、Spring で AspectJ アノテーションを使用できます (「 7.2 @AspectJ のサポート):
@Aspect
public class AroundExample {
@Around("@annotation(...)")
public Object invoke(ProceedingJoinPoint pjp) throws Throwable {
...
}
}
所属していません StackOverflow