我想使用Guice和AOP支持来记录方法执行时间。我能够将执行时间打印到控制台,但我想将它传递给另一个对象。我的代码是:
GuicePerfMeter.java类
public class GuicePerfMeterApp {
@Inject
private RestClient client;
public static void main(String[] args) {
Injector injector = Guice.createInjector(new GuicePerfMeterAppModule());
GuicePerfMeterApp app = injector.getInstance(GuicePerfMeterApp.class);
new Result(1, app.client.waitAndGetName()); //Instead of 1 I would like to have execution time
}}
GuicePerfMeterAppModule.java
public class GuicePerfMeterAppModule extends AbstractModule {
protected void configure() {
bindInterceptor(Matchers.any(), Matchers.annotatedWith(MeasurePerformance.class),
new PerformanceMeter());
}}
MeasurePerformance.java
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface MeasurePerformance {
}
PerformanceMeter.java
public class PerformanceMeter implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object obj = invocation.proceed();
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("Execution time: " + executionTime);
return obj;
}}
RestClient.java
public class RestClient {
@MeasurePerformance
String waitAndGetName() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Testing";
}}
Result.java
public class Result {
private long executionTime;
private String name;
public Result(long executionTime, String name) {
this.executionTime = executionTime;
this.name = name;
}}
这是我创建的课程。我希望结果对象的执行时间充满在拦截器中测量的执行时间。任何想法的人?