"Annotation type not applicable to this kind of declaration" 当使用来自 JAX-RS 的 @QueryParam 和 @DefaultValue 时

"Annotation type not applicable to this kind of declaration" when using @QueryParam and @DefaultValue from JAX-RS

我收到以下编译错误:

Error(35,13):  annotation type not applicable to this kind of declaration
Error(36,13):  annotation type not applicable to this kind of declaration
Error(38,13):  annotation type not applicable to this kind of declaration
Error(39,13):  annotation type not applicable to this kind of declaration
Error(41,13):  annotation type not applicable to this kind of declaration
Error(42,13):  annotation type not applicable to this kind of declaration

所有这些错误都是针对 Jersey 的 @ParamValue@DefaultValue 注释。我在互联网上看到很多例子,他们都说 Jersey 允许字符串 class 和所有包装器 classes。我不明白为什么它在这里不起作用。

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

@Path("/sracows")
public class sracoWebService {

    public sracoWebService() {
        super();
    }

    @GET
    @Path("/empdata")
    public String getEmployeeData() throws Exception {
        try {
            @DefaultValue("nationality")
            @QueryParam("nationality")
            String nationality;
            @DefaultValue("experience")
            @QueryParam("experience")
            String experience;
            @DefaultValue("empid")
            @QueryParam("empid")
            String empid;
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

两个@QueryParam and @DefaultValue注解可以放在资源方法参数资源class 字段 资源 class bean 属性 .

您的注释位于 局部变量 上,这就是您出现编译错误的原因。

你可以...

@Path("/foo")
public class MyResourceClass {

    @GET
    @Path("/bar")
    public String myResourceMethod(
        @QueryParam("nationality") @DefaultValue("nationality") String nationality, 
        @QueryParam("experience") @DefaultValue("experience") String experience,
        @QueryParam("empid") @DefaultValue("empid") String empid) {

        ...
    }
}

你可以...

@Path("/foo")
public class MyResourceClass {

    @QueryParam("nationality")
    @DefaultValue("nationality")
    private String nationality;

    @QueryParam("experience")
    @DefaultValue("experience")
    private String experience;

    @QueryParam("empid")
    @DefaultValue("empid")
    private String empid;

    @GET
    @Path("/bar")
    public String myResourceMethod() {
        ...
    }
}

你可以...

public class ParameterAggregator {

    @QueryParam("nationality")
    @DefaultValue("nationality")
    private String nationality;

    @QueryParam("experience")
    @DefaultValue("experience")
    private String experience;

    @QueryParam("empid")
    @DefaultValue("empid")
    private String empid;

    // Getters and setters
}
@Path("/foo")
public class MyResourceClass {

    @GET
    @Path("/bar")
    public String myResourceMethod(@BeanParam ParameterAggregator params) {
        ...
    }
}