SpringBoot(一)学习笔记
SpringBoot 入门 SpringBoot 的设计思想是:约定优于配置
SpringBoot 的优点:
1、遵循“约定优于配置”的原则,使用 SpringBoot 只需要很少的配置或使用默认的配置
2、使用 JavaConfig,避免使用 XML 的繁琐
3、提供 Starters(启动器),简化 Maven 配置,避免依赖冲突
4、提供内置 Servlet 容器,可选择内嵌 Tomcat、Jetty 等容器,不需要单独的 Web服务器,这就意味着不再需要启动 Servlet 或其他任何中间件
5、提供了一系列项目中常见的非功能特性,如安全监控,应用监控,健康检测等
6、与云计算、微服务的天然集成
什么是“约定优于配置 ”: “约定优于配置”也被称作“按约定编程”,是一种软件设计范式,旨在减少软件开发者需要的配置项,这样既能使软件保持简单又不失灵活性;
Spring、SpringBoot、SpringCloud 的关系:
1、Spring 是一个开源的生态体系,是集大成者; 其核心是控制反转(Inversion of Controller,IoC)和面向切片编程(Aspect Oriented Programming,AOP) 正是 IoC 和 AOP 这两个核心功能成就了强大的 Spring,Spring 在这两大核心功能上不断地发展壮大,才有了 SpringMVC 等一系列成熟的产品,最终构建了功能强大的 Spring 生态帝国;
2、SpringBoot 是在 Spring 的基础上发展而来的,它不是为了取代 Spring,而是为了简化 Spring 应用的创建、运行、调试、部署,让开发者更容易的使用 Spring; 它将目前比较成熟的服务框架和第三方组件合起来,按照“约定优于配置”的设计思想进行重新封装,屏蔽掉复杂的配置和实现,最终给开发者提供一套简单、易用、易部署、易维护的分布式系统开发工具包;
3、SpringCloud 是基于 SpringBoot 实现的分布式微服务框架,它利用 SpringBoot 简单、易用、便捷的特性简化了分布式系统基础设施的开发; 如服务发现、服务注册、配置中心、消息总线、负载均衡、断路器、数据监控等基础组件都可以用 SpringBoot 的开发风格做到一键启动和部署;
SpringBoot 推荐的目录结构:
1 2 3 4 5 6 7 8 main + com.hqd.helloworld + common //全局功能类、全局的配置文件、工具文件类 + model //实体类 entity + repository //数据库访问层代码 dao + service //业务类代码 + web //controller、负责前台访问的 controller + Application.java //项目的启动类
简单的控制器例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package com.hqd.helloworld.web;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController public class HelloController { @RequestMapping("/hello") public String hello () { return "Hello @ SpringBoot!!!" ; } } @RestController 和 @Controller 两种控制器的区别:@RestController :返回客户端数据请求,主要用于 RESTful 接口;@Controller :返回数据和页面,处理 HTTP 请求可以说 @RestController 是: @Controller 与 @ResponseBody 的结合体,因而具有两个标注合并起来的作用 @RestController = @Controller + @ResponseBody ;
SpringBoot 单元测试 Maven 引入单元测试依赖:spring-boot-starter-test
1 2 3 4 5 6 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-test</artifactId > <scope > test</scope > </dependency >
编写单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 package com.hqd.helloworld;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest public class HelloTest { @Test public void hello () { System.out.println("Hello Spring Boot Test!" ); } }
配置开发环境热部署 Maven 引入依赖:spring-boot-devtools
1 2 3 4 5 6 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-devtools</artifactId > <optional > true</optional > </dependency >
//true:其他项目如果引入此项目生成的 JAR 包,则不会包含 devtools;如果想使用 devtools,需要重新引入;
开发环境热部署配置 1 2 3 4 5 6 7 8 # application.properties 文件中配置 devtools # 开启热部署 spring.devtools.restart.enabled=true # 设置重启的目录 spring.devtools.restart.additional-paths=src/main/java # classpath 目录下的 WEB-INF 文件夹内容修改不重启 spring.devtools.restart.exclude=WEB-INF/**