6

What does the parameter in @RestController("/path/..") do? Does it not set the base path like @RequestMapping("/path/.."). What is the difference?

@RestController("base-path")
Peter Becker
  • 8,795
  • 7
  • 41
  • 64
Kranthi
  • 133
  • 2
  • 10
  • On a side note: @ RequestMapping = Routing information that will be used by spring. Whereas @ RestController = @ Controller + @ ResponseBody – Prashant Zombade Mar 01 '23 at 03:53

3 Answers3

4

Taken from the Spring Documentation:

  • @RestController -

is known as a stereotype annotation. It provides hints for people reading the code, and for Spring, that the class plays a specific role. ... so Spring will consider it when handling incoming web requests.

  • @RequestMapping -

annotation provides “routing” information. It is telling Spring that any HTTP request with the path “/” should be mapped to the home method. The @RestController annotation tells Spring to render the resulting string directly back to the caller.

Walter G.
  • 135
  • 4
  • 12
3

In case of @RestController the parameter value depicts the component name or bean name, whereas in @RequestMapping the value parameter is used to specify the path. Both are used for different purpose.

If you want to specify request URI path on controller class name use @RequestMapping annotation with @RestController. Something like this:

@RequestMapping("/my-path")
@RestController
class MyController {
    ...
}
Saheb
  • 1,392
  • 3
  • 13
  • 33
  • where can we use the Component name or bean name if we set it ?. Is it for use in getBean() method ? – Kranthi Feb 20 '18 at 17:47
  • Yes it can be used there or while auto wiring beans, it can be used in qualifiers. However, controllers should never be auto-wired. – Saheb Feb 20 '18 at 17:50
  • If it is used as a component name, Then why does it work when `@RestController("/base")` is used and url contains `url.com/base` ? – Arun Gowda May 04 '21 at 07:41
  • it works as a component name only for the annotation which is meant to define components. `@RestController` is meant to define a component. `@RequestMapping` is meant to define the path. – Saheb May 06 '21 at 07:43
0

@RequestMapping methods assume @ResponseBody semantics by default . @RequestMapping is relatively traditional.

@RestController which combined the behavior of @Controller and @ResponseBody together. @RestController is relatively new.

Tushar
  • 1
  • 1