【问题标题】:Do i need @Produces when I declare type in function [duplicate]当我在函数中声明类型时我需要@Produces [重复]
【发布时间】:2021-10-21 15:12:56
【问题描述】:

我了解到在每个端点上编写 @Consumes@Produces 注释是很好的编程。但是,如果我在端点声明类型,我还需要注解吗?

什么是好的编程?

@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/pdf") // Content type declared in annotation
@Path(GET_BILL_FOR_SYSTEM)
public Response getBillForTheSystem(@QueryParam(value = "year") Long year) {
    return Response.ok( billSheetService.getBillForTheSystem(year) )
            .type( "application/pdf" ) // Content type declared in response builder
            .header( "Content-Disposition", "attachment; filename=\"BillForTheSystem.pdf\"" )
            .build();
}

【问题讨论】:

    标签: java rest jax-rs


    【解决方案1】:

    你是对的。两次声明响应内容类型的值没有功能上的原因。事实上,这样的重复往往是不受欢迎的。

    但是,如果您有检查代码以生成文档的工具,它可能能够读取注释,但不能读取代码本身返回的类型。所以在这种情况下,我宁愿只留下注释。

    【讨论】:

    • 它实际上用于内容协商。这不是重复。一个用于响应,另一个用于请求。注释将告诉请求者 application/pdf 是端点生成的内容。因此,当客户端使用不是 application/pdf 的 Accept 标头时,它将获得 406 Not Acceptable 响应。这是应该预料到的,也是好的做法。始终使用注释。
    • @PaulSamsotha 所以,我们应该只使用注释。重复仍然很糟糕。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2021-03-09
    • 2023-01-13
    • 1970-01-01
    相关资源
    最近更新 更多