简体   繁体   中英

Spring Converter<S, T> for @RequestParam and Spring Data REST

I'm using Spring Boot 1.2.6 and Spring Data REST latest release.

The documentation states that Converter<S, T> instances are auto-registered but it seems to work only for Sping WebMVC. I'm using the Spring Data REST's @RepositoryRestController for my controller.

My use case method declaration is the following:

public PagedResources<Resource<Equipment>> filterEquipments(
    @RequestParam("page") Integer page,
    @RequestParam("sort") String sort,
    @RequestParam("filter") MyFilter filter, // I want to register custom converter for this type
    PersistentEntityResourceAssembler resourceAssembler) {
    // method body
}

The Converter (dummy of it yet):

@Component
public class MyFilterConverter implements Converter<String, MyFilter> {
    @Override
    public MyFilter convert(String source) {
        return new MyFilter();
    }
}

I have also followed the advice of this question , but it does not seem to work for @RepositoryRestController either.

How can I add custom converter to Spring Data REST custom controllers? (Not using manual passing of reference to a converter to the Controller).

Here's one solution to register your custom type Converter instance(s) at startup (should then be applied to controller method params of type MyFilter ):

@Configuration
public class WebConfig {

    @Autowired
    private ConverterRegistry converterRegistry;

    @PostConstruct
    public void init() {
        registerConverters();
    }

    private void registerConverters() {
        converterRegistry.addConverter(new MyFilterConverter());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM