springboot项目target_Spring Boot从入门到精通-初识注解、rest接口

本文介绍了Spring Boot项目中如何使用@RestController和@GetMapping注解创建REST接口,并通过分析源码理解其作用。在Spring Boot中,@SpringBootApplication注解帮助自动扫描组件,简化配置。内容包括@RestController与@Controller和@ResponseBody的关系,以及@GetMapping与@RequestMapping的差异。
摘要由CSDN通过智能技术生成

在上一节中我们搭建了一个简单的Spring Boot项目。在这一节中我们来根据项目初步了解Spring Boot中常用的注解。

首先在启动类同级目录下新建controller目录,在controller目录中新建java类:DemoController.java

d0d1e9ea39e963843f18a8ee79120757.png

项目结构

在DemoController.java中我们利用注解实现一个简单的接口。

@RestControllerpublic class DemoController { @GetMapping("/test") public String test() { return "test"; }}

可以看到在这个类中使用了两个注解,@RestController和 @GetMapping。

启动项目,在浏览器中输入:http://localhost:8080/test

可以看到浏览器中输出test字符。

接下来分析代码。

查看RestController的源码如下:

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Controller@ResponseBodypublic @interface RestController { @AliasFor( annotation = Controller.class ) String value() default "";}

从RestController 源码中可以看到RestController 注解了@Controller和@ResponseBody。因此这个接口可以返回数据。

关于更多的注解详解可以点击这里

查看GetMapping的源码如下:

@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documented@RequestMapping( method = {RequestMethod.GET})public @interface GetMapping {...

从GetMapping 源码中可以看到注解了RequestMapping而且赋予了get类型。

也就是说@GetMapping的作用等同于@RequestMapping(method = {RequestMethod.GET})而且更加简洁。

在以往的spring项目中,单单注解了@Controller或者@RestController加上@RequestMapping还不能真正意义上的说它就是SpringMVC 的一个控制器类,因为这个时候Spring 还不认识它。需要通过在xml中配置扫描包路径或者在xml中单独配置这个java类,而在Spring Boot中完全免去了这一步。Spring Boot默认扫描启动类同级目录下的所有文件,所以在这里无需其他的xml配置直接就可以直接访问接口。

@SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}

在项目的启动类中,发现idea默认为我们加上了一个注解@SpringBootApplication,查看SpringBootApplication源码如下:

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class}), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class})})public @interface SpringBootApplication {...

我们先关注SpringBootApplication 上的@ComponentScan,这个注解就是指引项目启动之后spring扫描包的路径,如果你不希望spring在项目启动时扫描全局,那么可以在启动类中使用这个注解来配置spring的扫描路径。缩小扫描的范围可以缩短项目启动时间。

@SpringBootApplication@ComponentScan(basePackages={"com.example.demo.controller"})public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}

在这一节中,我们了解到了一些Spring Boot常用的注解以及写了一个rest接口。在下一节我们将详细的对Spring boot的注解进行分析Spring Boot从入门到精通-注解详解

您的关注是我最大的动力

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值