在JAX-RS中选择参数转换器

时间:2019-03-01 22:08:01

标签: java jax-rs

说我有

class Person {
  int id;
  String name;
}

和资源:

class CountryCodeResource {
  @GET public String getCountryCodeByPersonId(@QueryParam("id") Person person) { ... }
  @GET public String getCountryCodeByPersonName(@QueryParam("name") Person person) { ... }
}    

我可以针对每种情况做出ParamConverter

class PersonByIdParamConverter implements ParamConverter<Person> {
  @Override public Person fromString(String value) {
    int personId = Integer.toString(value);
    return lookUpPersonById(personId);
  }

  @Override public String toString(Person person) { ... }
}

class PersonByNameParamConverter implements ParamConverter<Person> {
  @Override public Person fromString(String value) {
    return lookUpPersonByName(value);
  }

  @Override public String toString(Person person) { ... }
}

如何指定要使用哪个?即jax-rs中有与此类似的东西吗?

class CountryCodeResource {
  @GET public String getCountryCodeByPersonId(@QueryParam("id")
    @ParamConverter(PersonByIdParamConverter.class) Person person) { ... }

  @GET public String getCountryCodeByPersonName(@QueryParam("name")
    @ParamConverter(PersonByNameParamConverter.class) Person person) { ... }
}    

0 个答案:

没有答案