【问题标题】:Anonymous JAX-RS Resources匿名 JAX-RS 资源
【发布时间】:2014-05-28 08:39:29
【问题描述】:

我正在寻找在运行时创建 JAX-RS 资源的任何可能性(对于实体类)。通常这些类会使用@Path("/<resource>") 进行注释,以将它们标识为资源类。是否可以在运行时创建这些类,例如作为具有自定义路径的匿名类?

这里是它的样子,而抽象服务是一个基本实现:

AnyType service = new AbstractService() {
  @Path("/<CustomResourceName>")
  public Collection<Resource> getAll() {
    return dao.getAll(Resource.class);
  }
}

之后当然必须以某种方式注册服务。

谢谢!!

【问题讨论】:

  • 为什么不为所有自动生成的 Rest 资源添加前缀?
  • 那不会是问题,问题是要为每个资源自定义路径

标签: java jax-rs soa


【解决方案1】:

解决方法如下:

@Path("/dynamic-classes")
public class DynamicRestResource {
    private static final Map<String, Class<?>> CLASS_NAME_MAP = Collections.unmodifiableMap(new HashMap<String, Class<?>>(){
        private static final long serialVersionUID = 1L;

    {
            put(MyClass1.class.getSimpleName().toLowerCase(), MyClass1.class);
            put(MyClass2.class.getSimpleName().toLowerCase(), MyClass2.class);
                        //... put here your other classes.
            }}
    );
  private Class<?> getMappedClass(String mappedPath) {
    return CLASS_NAME_MAP.get(mappedPath);
  }

  @GET
  @Path("/{className}")
  public Collection<?> getAll(@PathParam("className") String className) {
    //do some checks that there is such a path
    return dao.getAll(this.getMappedClass(className));
  }

  @DELETE
  @Path("/{className}/{entityId}")
  public Collection<?> deleteEntity(@PathParam("className") String className, @PathParam("entityId") Long entityId) {
    //do some checks that there is such a path
    return dao.delete(this.getMappedClass(className), entityId);
  }
}

【讨论】:

    猜你喜欢
    • 2010-12-21
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2019-03-01
    • 2015-05-05
    相关资源
    最近更新 更多