我正在尝试使用Aspect
使用Around建议为javax.ws.rs.core.Response
添加时间戳。
我是Java和泽西的新手,我正努力做到这一点。我最接近的是:
Object output = proceed();
Method method = ((MethodSignature) thisJoinPoint.getSignature()).getMethod();
Type type = method.getGenericReturnType();
if (type == Response.class)
{
System.out.println("We have a response!");
Response original = (Response) output;
output = (Object)Response.ok(original.getEntity(String.class).toString()+ " " + Double.toString(duration)).build();
}
return output;
产生的响应类型始终为application/JSON
。基本上我想在JSON中添加另一个字段time:<val of duration>
。
答案 0 :(得分:0)
最简单的解决方案是让所有实体类扩展一个具有方法getTime()
和setTime()
的接口,然后您可以在拦截器中设置时间值,如下所示。
public interface TimedEntity {
long getTime();
void setTime(long time);
}
您的实际实体
public class Entity implements TimedEntity {
private long time;
// Other fields, getters and setters here..
@Override
public long getTime() {
return time;
}
@Override
public void setTime(long time) {
this.time = time;
}
}
你的拦截器
Object output = proceed();
Method method = ((MethodSignature)thisJoinPoint.getSignature()).getMethod();
Type type = method.getGenericReturnType();
if (type == Response.class)
{
System.out.println("We have a response!");
Response original = (Response) output;
if (original != null && original.getEntity() instanceof TimedEntity) {
TimedEntity timedEntity = (TimedEntity) original.getEntity();
timedEntity.setTime(duration);
}
}else if (output instanceof TimedEntity) {
TimedEntity timedEntity = (TimedEntity) output;
timedEntity.setTime(duration);
}
return output;