您应该能够将绑定添加到 MessageBodyWriter 的实现,而不是扫描包。例如:
public class Config extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(
new JerseyServletModule() {
@Override
protected void configureServlets() {
bind(Service.class);
bind(CsvWriter.class);
serve("/services/*").with(GuiceContainer.class);
}
});
}
}
CsvWriter.java 看起来像:
@Singleton
@Produces("text/csv")
@Provider
public class CsvWriter implements MessageBodyWriter<Foo> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Foo.class.isAssignableFrom(type);
}
@Override
public long getSize(Foo data, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType) {
return -1;
}
@Override
public void writeTo(Foo data,
Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> headers,
OutputStream out) throws IOException {
// Serialize CSV to out here
}
}
然后在服务中有一些@Produces(“text/csv”)的方法。