簡單的例子

截獲方法:

public class ExampleService implements Example {
    @MyAnnotation
    public doHomework() {
        System.out.println("working");
    }
}

註解:

    @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
    public @interface MyAnnotation {}

攔截器:

public class MyInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation arg0) throws Throwable {
        System.out.println("***** intercepted *****");
        return arg0.proceed();
    }
}

模組:

public class MyModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(CallerService.class).to(Caller.class);
        bind(ExampleService.class).to(Example.class);

        bindInterceptor(Matchers.any(), Matchers.annotatedWith(MyAnnotation.class), new MyInterceptor());
    }
}

呼叫者:

public class CallerService implements Caller {
    @Inject
    private Client client;

    public void call() {
        client.doHomework();
    }
}

輸出:

***** intercepted *****
working