是否可以定义与其实现分离的 jax-rs 服务接口(使用 eclipse 和 jersey)?接口、定义、jax、rs

2023-09-06 15:04:25 作者:总有人恋爱一生

我不知道标题是否令人困惑,但假设我有这个界面:

I don't know if the title is confusing, but let's say I have this interface:

@Produces(MediaType.APPLICATION_JSON)
@Path("/user")
public interface UserService {

    @GET
    @Path("/{userId}")
    public Response getUser(@PathParam("userId") Long userId);

}

为什么当我尝试实现一个版本时,Eclipse 会为被覆盖的方法而不是类重写注释?

Why when I try to implement a version Eclipse rewrites annotation for the overridden method but not for the class?

class UserServiceImpl implements UserService {

    @Override
    @GET
    @Path("/{userId}")
    public Response getUser(@PathParam("userId") Long userId) {
        // TODO Auto-generated method stub
        return null;
    }

}

我试图为 restful web 服务创建一个标准定义,然后有不同的实现.使用标准 jax-rs 可以实现这样的事情吗?我是否有任何机会使用错误的注释?

I was trying to create a standard definition for the restful web service and then having different implementations. Is something like this possible with standard jax-rs? Am I using wrong annotations by any chance?

推荐答案

只有在不使用any jax-rs注解的情况下才能使用注解继承实现类:在 JSR-339 的 3.6 节中有说明.

You can use annotation inheritance only if you don't use any jax-rs annotation on the implementing class: it is stated on section 3.6 of JSR-339.

您为方法而不是类重新定义 @Path@Produces.

You redefine @Path and @Produces for the method but not for the class.

所以代码中的 Path 注释应该在具体类上:

So the Path annotation in your code should be on the concrete class:

public interface UserService {

    @GET
    @Path("/{userId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUser(@PathParam("userId") Long userId);

}


@Path("/user")
class UserServiceImpl implements UserService {

    @Override
    @GET
    @Path("/{userId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUser(@PathParam("userId") Long userId) {
        // TODO Auto-generated method stub
        return null;
    }

}

顺便说一句,规范鼓励我们在具体类上复制注释:

BTW, the specification encourages us to replicate the annotations on the concrete classes:

为了与其他 Java EE 规范保持一致,建议始终重复注解来代替依赖注解继承.

For consistency with other Java EE specifications, it is recommended to always repeat annotations instead of relying on annotation inheritance.