Spring Boot从入门到精通-初识注解、rest接口 - Go语言中文社区

Spring Boot从入门到精通-初识注解、rest接口


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

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

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

@RestController
public 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
@ResponseBody
public @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配置直接就可以直接访问接口。

@SpringBootApplication
public 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从入门到精通-注解详解

您的关注是我最大的动力

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq1311256696/article/details/86528427
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-06-30 10:45:28
  • 阅读 ( 1247 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢