Nickknack
Nickknack

Reputation: 857

Spring @PathVariable as a Year

I've got an endpoint that is:

api/entities/{year}

and my function looks like:

get(@PathVariable(name = "year") Year year)

But when I try to hit the endpoint I, expectedly, get an error that it can't convert from type String to type Year. I obviously need something like a @DateTypeFormat, but that doesn't really work.

Is there a way to format the incoming value to be a Year, or should I rework my API to not use a Year?

Upvotes: 3

Views: 303

Answers (3)

Paizo
Paizo

Reputation: 4194

An easy way is to accept an Integer and then convert it if you really need a Year type.

You can register your own HandlerMethodArgumentResolver to do the conversion for you although it looks like too much boiler plate for this scenario it is the more elegant.

Another possibility is to handle it as a date, that conversion comes for free:

@PathVariable(name = "year") @DateTimeFormat(pattern = "yyyy") Date date

You can later extract the year value in the form you prefer.

Upvotes: 1

Jaiwo99
Jaiwo99

Reputation: 10017

You can do something like:

public class YearHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(Year.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        final String yearFromPath = nativeWebRequest.xxx();

        return Year.from(yearFromPath);
    }

}

Then Register it in your spring-context

Upvotes: 7

dimwittedanimal
dimwittedanimal

Reputation: 656

You could accept it as a String and attempt to convert after the endpoint is hit?

Upvotes: 1

Related Questions