之前写了几个简单的入门程序,这篇对程序中的常用注解进行简单的讲解。首先我们先看启动类中的注解
一.@SpringBootApplication
在SpringBoot中,*Application类就是启动类,是SpringBoot启动的入口,
那么他是怎么知道这是一个入口的呢,就是凭借 @SpringBootApplication这个注解。之前有些SpringBoot应用会有一堆注解这里只用一个,原因就是 @SpringBootApplication是一个复合注解,我们点击 @SpringBootApplication进入源码查看,发现里面有很多元注解(不懂注解的可以看我之前的博客https://blog.csdn.net/qq_33355821/article/details/85371187),只要在上面打上@SpringBootApplication,也就是相当于加上了下面的注解,我们将@SpringBootApplication换成@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan也是可以
@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@bean注解标记的方法的实例纳入到Spring容器中,并且实例名就是方法名。
@EnableAutoConfiguration的作用启动自动的配置,@EnableAutoConfiguration注解的意思就是SpringBoot根据你添加的jar包来配置你项目的默认配置,比如根据spring-boot-starter-web,来判断你的项目是否需要添加了webmvc和tomcat,就会自动的帮你配置web项目中所需要的默认配置。在下面博客会具体分析这个注解,快速入门的demo实际没有用到该注解。
@ComponentScan扫描当前包及其子包下被@Component,@Controller,@Service,@Repository注解标记的类并纳入到spring容器中进行管理。是以前的<context:component-scan>(以前使用在xml中使用的标签,用来扫描包配置的平行支持)。所以本demo中的HelloController为何会被Spring容器管理。
二.@RestController
@RestController 其实就相当于SpringMVC中的 @Controller+@ResponseBody,就表示当前是一个controller组件并且返回json数据,这就特别方便前后端分离使用restful方式返回数据,下面进行实例演示,在SpringBootDemo3中加一个RestAnoController:
@RestController
public class RestAnoController {
@RequestMapping("/testMap")
public Map<String,String> testRestAno(){
HashMap newMap = new HashMap();
newMap.put("name","張三");
newMap.put("age","22");
return newMap;
}
}
启动运行并测试,我们可以发现返回的就是json数据
如果我们不加RestController直接加一个@Controller看看会有什么结果
如图所示就会报错,他会尝试返回一个解析视图给前端,但是失败了,所以如果我们要返回一个json数据就需要加上@RestController注解
其他与@RequestMapping相关的注解会在下篇讲解
源码地址:https://gitee.com/xuxinsunqizheng/SpringBoot2.0.git