同一RestEndpoint映射两个不同方法:如何根据produces匹配调用?
produces on the Same Endpoint Absolutely! This is exactly what the produces attribute is designed to handle in Spring MVC (which your code is using). Let me break down how this works clearly:
Core Idea
Spring MVC uses the Accept HTTP request header sent by the client to match against the produces value of your controller methods. That's the key mechanism here.
Using your example:
- The
getUser()method is set to produceapplication/json(viaMediaType.APPLICATION_JSON_VALUE) - The
getBinUser()method producesapplication/octet-stream(viaMediaType.APPLICATION_OCTET_STREAM_VALUE)
How Clients Trigger Each Method
Here's how different client requests will route to the right method:
- When the client sends
Accept: application/json: Spring will callgetUser(), since itsproducesvalue matches the requested media type. - When the client sends
Accept: application/octet-stream: The request will go togetBinUser()instead. - If no
Acceptheader is sent: Spring usually defaults to the first matching method it finds (but it's better to always specify theAcceptheader to avoid ambiguity).
Test with curl
You can easily test this with curl commands:
- Call
getUser():curl -H "Accept: application/json" http://your-server-address/v1/v2/123 - Call
getBinUser():curl -H "Accept: application/octet-stream" http://your-server-address/v1/v2/123
Edge Cases to Keep in Mind
- Multiple
Acceptvalues: If the client sends something likeAccept: application/json, application/octet-stream;q=0.8, Spring uses content negotiation rules to pick the highest-priority match (theqvalue is the quality factor, higher means more preferred). - No matching media type: If the client requests a type neither method supports (like
text/plain), Spring will return a406 Not Acceptableerror.
Quick Summary
Yes, the produces attribute directly determines which method is called, and the client needs to send the corresponding Accept header to target the right one. This is a standard REST pattern for serving different representations of the same resource.
内容的提问来源于stack exchange,提问作者CuriousMind

