2017-12-03 241 views
0

JAX-RS帕拉姆轉換器 - 編譯時錯誤,這是我的PARAM轉換器使用它

import org.springframework.data.domain.Sort; 

public class MyParamConverter implements ParamConverter<Sort> { 
    @Override 
    public Sort fromString(String s){ 
     return new Sort(new Sort.Order(Sort.Direction.ASC, "ds")); 
    } 

    @Override 
    public String toString(Sort mo){ 
     return mo.toString(); 
    } 

} 

這是我paramconverter提供商

@Provider 
public class MyParamConverterProvider implements ParamConverterProvider { 

@Override 
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { 
    if(rawType.equals(Sort.class)){ 
     return (ParamConverter<T>) new MyParamConverter(); 
    } 
    return null; 
} 

我想在我的API使用,因爲

@GET 
@Path("/") 
Response read(@QueryParam("sort") Sort order); 

我期待的jax映射字符串,我通過我的url例如&sort="asc"來排序對象。但是我得到編譯時錯誤have a registered implementation of paramconverter provider。當我通過查詢參數&sort="somethung"時,我需要找到一種方法,通過使用自定義註釋或使用Param Converter自動轉換爲SORT

+0

? – sschrass

+0

@sschrass。那就是問題所在。我不知道如何註冊提供商。 – user3678399

回答

0

參考您的意見,嘗試註冊您的供應商,如:

@ApplicationPath("/") 
public class MyApplication extends ResourceConfig { 

    @Override 
    public Set<Class<?>> getClasses() { 
     final Set<Class<?>> classes = new HashSet<Class<?>>(); 
     classes.add(MyParamConverterProvider.class); 

     return classes; 
    } 
} 

或者,如果您有您註冊的供應商使用澤西

@ApplicationPath("/") 
public class MyApplication extends ResourceConfig { 

    public MyApplication() { 
     packages("my.package"); 

     // or without package scanning 
     register(MyParamConverterProvider.class); 
    } 
} 
+0

感謝您的更新。我會嘗試使用它。你能告訴我爲你的答案的選項1的ResourceConfig或Maven依賴項的導入。 因爲我害怕我使用錯誤的。 – user3678399

+0

因爲當我使用選項1時,它說不能覆蓋getClasses()作爲超級類中的最終成績 – user3678399

+0

我推薦使用Jersey。本教程中還有一個Spring-Boot啓動器:https://howtodoinjava.com/spring/spring-boot/spring-boot-jersey-example/否則將您的依賴關係添加到您的問題中,很難找出你正在使用的是什麼。 – sschrass