我很難理解Jersey的注入機制。 JAX-RS規範(http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-520005)規定,應用程序子類,根資源類和提供程序可以通過@Context進行注入。Jersey @Context範圍
我現在有一個在啓動時實例化的類,它有一個在每個請求上調用的方法。在該方法內我需要訪問當前的UriInfo對象。問題是,這個方法不是從我的代碼中調用的。所以我無法直接將UriInfo傳遞給該方法。
其實我是想這樣做:
public class MyClass implements ThirdPartyInterface {
// not possible because class is no Application subclass, root resource class or provider
@Context
private UriInfo uriInfo;
public void methodCallebByThirdPartyCode() {
Uri requestUri = uriInfo.getRequestUri();
// do something
}
}
我嘗試這樣做。顯然沒有成功:
public class MyClass implements ThirdPartyInterface {
private UriInfo uriInfo;
public MyClass(UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
public void methodCallebByThirdPartyCode() {
Uri requestUri = uriInfo.getRequestUri();
// do something
}
}
@Provider
@Produces(MediaType.WILDCARD)
public class MyBodyWriter implements MessageBodyWriter<MyView> {
@Context
private UriInfo uriInfo;
private MyClass myClass;
private ThirdPartyClass thirdPartyClass;
public MyBodyWriter() {
// uriInfo is null at this time :(
myClass = new MyClass(uriInfo);
thirdPartyClass = new ThirdPartyClass();
thirdPartyClass.register(myClass);
}
public void writeTo(final MyView view, final Class<?> type, /* and so on */) throws IOException, WebApplicationException {
// execute() calls MyClass#methodCallebByThirdPartyCode()
thirdPartyClass.execute();
}
}
我能想到的唯一的解決方法是這樣的。我不認爲它很乾淨:
public class MyClass implements ThirdPartyInterface {
private UriInfo uriInfo;
public void setUriInfo(final UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
public void methodCallebByThirdPartyCode() {
Uri requestUri = uriInfo.getRequestUri();
// do something
}
}
@Provider
@Produces(MediaType.WILDCARD)
public class MyBodyWriter implements MessageBodyWriter<MyView> {
@Context
private UriInfo uriInfo;
private MyClass myClass;
private ThirdPartyClass thirdPartyClass;
public MyBodyWriter() {
myClass = new MyClass();
thirdPartyClass = new ThirdPartyClass();
thirdPartyClass.register(myClass);
}
public void writeTo(final MyView view, final Class<?> type, /* and so on */) throws IOException, WebApplicationException {
myClass.setUriInfo(uriInfo);
// execute() calls MyClass#methodCallebByThirdPartyCode()
thirdPartyClass.execute();
myClass.setUriInfo(null);
}
}
我希望有一個更好的解決方案,但也許我完全在錯誤的軌道上。
謝謝!
也許你只需要'ContainerRequestFilter'? – Willy 2013-05-08 02:34:54
我不知道這是否適合我的情況。規範說「提供者類由JAX-RS運行時實例化」。但是我需要在施工時參考對象,將它傳遞給第三方服務。 – 2013-05-08 10:01:35