@RestController注解、@RestController注解中value作用、@RestController 指定主路径无效踩坑

文章讲述了在使用Spring的@RestController注解时,如何正确指定主路径以及value属性的作用。指出value属性是建议值,而非路径,应使用@RequestMapping明确路径。同时,分析了@RestController注解相当于@Controller和@ResponseBody的组合,以及返回不同格式内容的注意事项。
摘要由CSDN通过智能技术生成

一、@RestController 指定主路径无效踩坑

指定路径时写成了 @RestController(“user”), 测试接口的时候发现无效。在这里插入图片描述
查看源码关于 value 的说明:
在这里插入图片描述
这仅仅是建议值, 实际应该使用@RequestMapping("/user") 指定.

package com.demo.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController("/user")
public class UserController {
    
    
    @GetMapping("/list")
    public void list(){
    }

}

二、@RestController注解

@RestController注解相当于@ResponseBody + @Controller合在一起的作用。

  1. 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
    例如:本来应该到success.jsp页面的,则其显示success.

  2. 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。

  3. 如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

2.1、@RestController注解中value作用

查看@RestController注解内部源码如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";

}

@RestController的小括号当中填写的内容,相当于@Service(“”)当中填写的内容,即spring bean的名称;

The value may indicate a suggestion for a logical component name, 
to be turned into a Spring bean in case of an autodetected component.
该值可能表示一个逻辑组件名称的建议,在自动检测到组件的情况下,将其转换为Spring bean。

所以如果是要填写路径的话,还是需要使用@RequestMapping(“/user”)才是正确的;

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值