0
    @GET
    @Path("/book")
    public Response getBook(@BeanParam Filter filter) {

    }

过滤器参数正在初始化,但 bean 中没有设置任何内容

class Filter {@QueryParam("author")String author}

对于 Filter 对象中存在的所有属性,我确实有 setter 和 getter。

仅供参考,我正在使用 HK2 guice-bridge

4

2 回答 2

1

我能够用 guice-bridge 重现这个问题。似乎在初始化桥接器时(通过 guiceBridge.bridgeGuiceInjector(...)),仅调用 BeanParam 的默认构造函数,而不是设置属性(或使用参数调用构造函数)。

如果在您的项目中可能,您可以尝试为构造函数提供参数。

这是一个简单的应用程序:

public class App extends ResourceConfig {

   @Inject
   public App(final ServiceLocator serviceLocator) {
     register(Service.class);

     final Injector injector = initializeInjector(serviceLocator);
   }

   private Injector initializeInjector(final ServiceLocator serviceLocator) {
     GuiceBridge.getGuiceBridge()
         .initializeGuiceBridge(serviceLocator);

     final Injector injector = Guice.createInjector(
         new ApplicationModule(serviceLocator));
     final GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
     guiceBridge.bridgeGuiceInjector(injector);
     return injector;
   }

}

使用的服务:

@Path("service")
public class Service {

  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public Response save(@Valid @BeanParam final SimpleBean bean) {
    System.out.println(bean.getProperty());
    return Response.status(Status.CREATED)
        .build();
  }
}

这是一个简单的bean:

public class SimpleBean {

  // Avoid this constructor!
  // public SimpleBean() {
  //  System.out.println("constructor called");
  // }

  public SimpleBean(@FormParam("property") final String property) {
    this.property = property;
    System.out.println("constructor with params called: " + property);
  }

  @Length(max = 100)
  @NotBlank
  private String property;

  public String getProperty() {
    System.out.println("getter called");
    return property;
  }

  public void setProperty(final String property) {
    System.out.println("setter called with " + property);
    this.property = property;
  }

}

使用 Guice 版本 4.1.0、guice-bridge 版本 2.4.0、Jersey 版本 2.25.1 和 Javax servlet 版本 3.1.0。

于 2017-06-20T08:54:05.667 回答
0

您可以尝试使用没有桥接的 Guice-Jersey。有一个名为“Guice Webserver Module”的项目将 Guice 与 Jersey 2、Jetty 和 Jackson 集成在一起,实现了这种方法。

您需要做的是在 Guice 上下文中绑定您的资源,例如

public class MyModule extends AbstractModule() {
    public void configure() {
            bind(BooksResource.class);
    }

有一个 Jersey 的功能,它将扫描所有使用 @Path 注释的绑定,并在实例化后在 Jersey 的上下文中注册实例:

public boolean configure(FeatureContext context) {
    injector.getBindings().entrySet()
        .stream()
        .filter(entry -> entry.getKey().getTypeLiteral().getRawType().getAnnotation(Path.class) != null)
        .map(entry -> injector.getInstance(entry.getKey()))
        .forEach(context::register);

    return true;
  }

还有一个 BeanParams 的示例(作为集成测试的一部分编写) - BeanParamsIntegrationTest

于 2017-08-25T23:03:28.320 回答