微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Spring Data JPA方法REST:Enum to Integer转换

我有一个端点:

/apI/Offers/search/findByType?type=X

其中X应该是一个Integer值(我的OfferType实例的序数值),而Spring认为X是一个String,并将StringToEnumConverterFactory应用于StringToEnum转换器.

public interface OfferRepository extends PagingAndSortingRepositoryaram("type") OfferType type);

}

所以我写了一个自定义转换器< Integer,OfferType>它只是通过给定的序数得到一个实例:

public class IntegerToOfferTypeConverter implements Converter

然后我使用配置正确注册

@EnableWebMvc
@Configuration
@requiredArgsConstructor
public class GlobalMVCConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new IntegerToOfferTypeConverter());
    }

}

而且我被期望findByType?type = X的所有请求都将通过我的转换器,但它们没有.

有没有办法说定义为请求参数的所有枚举必须作为整数提供?此外,有什么方法可以在全球范围内说出来,而不仅仅是针对特定的枚举?

编辑:我在我的类路径中找到了IntegerToEnumConverterFactory,它可以满足我的所有需要​​.它在DefaultConversionService中注册,这是一个认的转换服务.怎么能应用?

编辑2:这是一件非常简单的事情,我想知道是否有一个属性可以转换枚举转换.

EDIT3:我试着写一个转换器< String,OfferType>在我从TypeDescriptor.forObject(value)获得String后,它没有帮助.

EDIT4:我的问题是我已经将自定义转换器注册放入MVC配置(带有addFormatters的WebMvcConfigurerAdapter)而不是REST存储库(RepositoryRestConfigurerAdapter with configureConversionService).

最佳答案
Spring将查询参数解析为字符串.我相信它总是使用Converter< String,?>转换器从查询参数转换为存储库方法参数.它使用增强型转换器服务,因为它注册its own converters,例如Converter< Entity,Resource>.

因此,您必须创建一个转换器< String,OfferType>,例如:

@Component
public class StringToOfferTypeConverter implements Converter

然后在扩展RepositoryRestConfigurerAdapter的类中配置此转换器以供Spring Data REST使用:

@Configuration
public class ConverterConfiguration extends RepositoryRestConfigurerAdapter {

    @Autowired
    StringToOfferTypeConverter converter;

    @Override
    public void configureConversionService(ConfigurableConversionService conversionService) {
        conversionService.addConverter(converter);
        super.configureConversionService(conversionService);
    }
}

我试着将它添加the basic tutorial,在Person类中添加一个简单的枚举:

public enum OfferType {
    ONE,TWO;
}


@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private OfferType type;


    public OfferType getType() {
        return type;
    }

    public void setType(OfferType type) {
        this.type = type;
    }
}

当我打电话给:

07002

我得到的结果没有错误

{
  "_embedded" : {
    "people" : [ ]
  },"_links" : {
    "self" : {
      "href" : "http://localhost:8080/people/search/findByType?type=1"
    }
  }
}

要实现全局枚举转换器,您必须使用以下方法创建工厂并在配置中注册它:conversionService.addConverterFactory().以下代码修改后的example from the documentation

public class StringToEnumFactory implements ConverterFactorytargettype) {
        return new StringToEnum(targettype);
    }

    private final class StringToEnum

原文地址:https://www.jb51.cc/spring/432521.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐