为什么Jersey在创建自己的PackagesResourceConfig时会说“数组包不能为null或为空”?

时间:2013-09-18 21:58:41

标签: java jersey jersey-1.0

我创建了自己的PackagesResourceConfig,如下所示:

import com.sun.jersey.api.core.PackagesResourceConfig;

import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

public class ResourceConfigClass extends PackagesResourceConfig {
    @Override
    public Map<String, MediaType> getMediaTypeMappings() {
        Map<String, MediaType> map = new HashMap<String, MediaType>();
        map.put("xml", MediaType.APPLICATION_XML_TYPE);
        map.put("json", MediaType.APPLICATION_JSON_TYPE);
        return map;
    }
}

但是现在当我启动我的应用时,它会给我一个错误,上面写着:

  

数据包数组不能为null或为空

来自泽西岛的这个源代码:

/**
 * Search for root resource classes declaring the packages as an 
 * array of package names.
 * 
 * @param packages the array package names.
 */
public PackagesResourceConfig(String... packages) {
    if (packages == null || packages.length == 0)
        throw new IllegalArgumentException("Array of packages must not be null or empty");

    init(packages.clone());
}

但是我已经通过设置com.sun.jersey.config.property.packages param在我的web.xml中设置了包,所以它不应该为null。

1 个答案:

答案 0 :(得分:2)

这实际上是一个Java问题。与带参数的普通构造函数不同,如果构造函数只有varargs,则无效传递是有效的。因此,您不会拥有来覆盖构造函数,就像使用StringInteger或任何非vararg参数一样。将我的课程改为此修复了问题:

import com.sun.jersey.api.core.PackagesResourceConfig;

import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

public class ResourceConfigClass extends PackagesResourceConfig {
    public ResourceConfigClass(String... packages) {    //this constructor needs to be here, do not delete it or else the com.sun.jersey.config.property.packages param can't be passed in.
        super(packages);
    }

    public ResourceConfigClass(Map<String, Object> props) { //this constructor needs to be here, do not delete it or else the com.sun.jersey.config.property.packages param can't be passed in.
        super(props);
    }

    @Override
    public Map<String, MediaType> getMediaTypeMappings() {
        Map<String, MediaType> map = new HashMap<String, MediaType>();
        map.put("xml", MediaType.APPLICATION_XML_TYPE);
        map.put("json", MediaType.APPLICATION_JSON_TYPE);
        return map;
    }
}