阅读目录
今天的最佳表现应该作为明天的最低要求
一、SpringBoot简介
摘自官方文档: SpringBoot官方文档
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need minimal Spring configuration.
翻译: SpringBoot可以容易的创建独立的、生产级别的、基于Spring的应用程序;我们对Spring平台和第三方库持有一种固执己见的观点,这样您就可以用最少的麻烦开始了。大多数Spring引导应用程序需要最少的Spring配置。
SpringBoot版本
截至目前的官方截图,最新稳定版本是2.5.6
- GA: 稳定版本,官方推荐使用此版本,在国外一般都是用GA表示RELEASE版本
- Release: 最终版本,Release不会以完整的单词出现在软件封面上,取而代之的是(R)
- RC: 该版本已经很成熟了,基本上不会存在Bug,与正式版本没什么差别
- M: 里程碑版本,表示该版本较之前的版本有比较大的改动
- SNAPSHOT: 快照版本,可以稳定使用,但是仍继续在改进(不建议使用)
- Beta: 该版本虽然有很大改进,但是依旧存在一些问题(不建议使用)
- Alpha:实现软件功能为主,Bug比较多(不建议使用)
- PRE: 预览版本,内部测试版本(不建议使用)
CURRENT表示的是当前的、最新的,CURRENT GA表示的是当前稳定版本
二、MVC模式
MVC简介
MVC是软件架构中的一种软件架构模式,它把系统分为模型层(Model)、视图层(View)、控制层(Controller)。
MVC模型
三、SpringBoot项目创建方式
1、通过官方的Spring initializr创建
创建地址: Spring initializr
填写好项目信息点击 GENERATE即可下载创建好的项目代码,导入编辑器即可。
2、通过IDEA Spring initializr创建
打开IDEA,选择创建项目,选择Spring initializr(官方初始化器)进行创建
创建好之后即可看到初始化器帮我们自动初始化好的项目结构。
3、通过Maven创建SpringBoot项目
打开IDEA,选择新建项目,使用Maven进行创建。
创建好之后的项目是空的,需要我们手动添加包、启动类、配置文件等
首先添加web依赖
- spring-boot-starter-parent 2.5.6版本
- spring-boot-starter-web 继承于 spring-boot-starter-parent,也是2.5.6版本,无需写版本号
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.5.6</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
然后创建包和项目启动类
@SpringBootApplication注解作用
@SpringBootApplication注解的作用是表明当前是一个SpringBoot工程,也是一个启动类,这是一个应用程序的入口。
启动类需要放在根目录下,而且加了此注解会自动的扫描启动类所在包及其子包中加了@Component注解的类,如果需要扫描启动所在包之外的类,那么需要自己重新定义扫描规则。使用@ComponentScan即可
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleSpringBootApplication.class,args);
}
}
@ComponentScan组件扫描
为什么@SpringBootAppplication注解可以实现自动扫描包的功能,因为此注解下面包含了@ComponentScan注解,此注解的作用就是扫描加了@Component注解的类。
@Component注解下面又有一个属性useDefaultFilters = true,该属性的作用是使用默认的Filter进行注解扫描,而Filter默认扫描启动类所在包及其子包下面带有@Component注解的类。
比如我们后面会使用到@Controller、@Service、@Mapper等注解都是@Component注解的衍生注解,所以都会被扫描到
四、第一个SpringBoot程序
在启动类所在包下新建一个controller包,然后新建一个ExampleController类
编写ExampleController里面的代码,返回 Hello SpringBoot2.x到浏览器
@Controller
public class ExampleController {
@RequestMapping(method = RequestMethod.GET,value = "/test")
@ResponseBody
public String test(){
return "Hello SpringBoot2.x";
}
}
运行项目并打开浏览器输入http://localhost:8080/test,按下回车即可看到返回的字符串。
@Controller注解的作用
语义上标注了这是一个控制器,其作用是将当前这个类注册成一个bean对象交给Spring容器管理。
@RequestMapping注解的作用
用于请求地址映射,作用在方法上,根据请求的路径,找到这个路径对应的方法,形成映射表。
@ResponseBody注解的作用
将方法的返回值,以特定的格式写入到response的body区域,进返回给客户端,当方法上面没有写@ResponseBody,底层会将方法的返回值封装为ModelAndView对象。
五、结束语
这就是SpringBoot2.x入门的基本知识,希望给每个学习SpringBoot2.x的小伙伴一点帮助。