我发现JAXB和Guice一起使用是可能的,但具有挑战性:两个库都"争夺"对对象创建的控制,您必须小心避免循环依赖,并且所有JAXB Adapters
和Guice Providers
之类的东西可能会变得混乱。我的问题是:
- 如何处理这个配置?什么一般策略/经验法则可以应用?
- 你能给我指出一个好的教程或编写良好的示例代码吗?
- 如何可视化依赖关系(包括
Adapters
和Providers
)?
对于一些示例代码,这里完成了一些示例工作:http://jersey.576304.n2.nabble.com/Injecting-JAXBContextProvider-Contextprovider-lt-JAXBContext-gt-with-Guice-td5183058.html
在写"错误?"的那行,输入推荐行。
I是这样的:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class[] types = { UserBasic.class, UserBasicInformation.class };
public JAXBContextResolver() throws Exception {
this.context =
new JSONJAXBContext(
JSONConfiguration.natural().build(), types);
}
public JAXBContext getContext(Class<?> objectType) {
/*
for (Class type : types) {
if (type == objectType) {
return context;
}
} // There should be some kind of exception for the wrong type.
*/
return context;
}
}
//My resource method:
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public JAXBElement<UserBasic> get(@QueryParam("userName") String userName) {
ObjectFactory ob = new ObjectFactory();
UserDTO dto = getUserService().getByUsername(userName);
if(dto==null) throw new NotFoundException();
UserBasic ub = new UserBasic();
ub.setId(dto.getId());
ub.setEmailAddress(dto.getEmailAddress());
ub.setName(dto.getName());
ub.setPhoneNumber(dto.getPhoneNumber());
return ob.createUserBasic(ub);
}
//My Guice configuration module:
public class MyServletModule extends ServletModule {
public static Module[] getRequiredModules() {
return new Module[] {
new MyServletModule(),
new ServiceModule(),
new CaptchaModule()
};
}
@Override
protected void configureServlets() {
bind(UserHttpResource.class);
bind(JAXBContextResolver.class);
serve("/*").with(GuiceContainer.class);
}
}