diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index 3ff3193..0000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Sync - -on: - push: - branches: [ master ] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - name: Sync to Gitee - uses: wearerequired/git-mirror-action@v1 - env: - # 注意在 Settings->Secrets 配置 GITEE_SSH_PRIVATE_KEY - SSH_PRIVATE_KEY: ${{ secrets.GITEE_SSH_PRIVATE_KEY }} - with: - # 注意替换为你的 GitHub 源仓库地址 - source-repo: "git@github.com:Snailclimb/springboot-guide.git" - # 注意替换为你的 Gitee 目标仓库地址 - destination-repo: "git@gitee.com:SnailClimb/springboot-guide.git" diff --git a/README.md b/README.md index c618fcf..e98b843 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,12 @@ +👍推荐[2021最新实战项目源码下载](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=100018862&idx=1&sn=858e00b60c6097e3ba061e79be472280&chksm=4ea1856579d60c73224e4d852af6b0188c3ab905069fc28f4b293963fd1ee55d2069fb229848#rd) + +👍[《JavaGuide 面试突击版》PDF 版本](#公众号) 。[图解计算机基础 PDF 版](#优质原创PDF资源) + +书单已经被移动到[awesome-cs](https://github.com/CodingDocs/awesome-cs) 这个仓库。 + + + +

@@ -10,62 +19,65 @@ 公众号 公众号

+**在线阅读** : https://snailclimb.gitee.io/springboot-guide (上面的地址访问速度缓慢的建议使用这个路径访问) -**在线阅读:** https://snailclimb.gitee.io/springboot-guide (上面的地址访问速度缓慢的建议使用这个路径访问) +**开源的目的是为了大家能一起完善,如果你觉得内容有任何需要完善/补充的地方,欢迎提交 issue/pr。** -## 重要知识点 +- Github地址:https://github.com/CodingDocs/springboot-guide +- 码云地址:https://gitee.com/SnailClimb/springboot-guide(Github无法访问或者访问速度比较慢的小伙伴可以看码云上的对应内容) -### 开始 - -1. **[Spring Boot 介绍](./docs/start/springboot-introduction.md)** -2. [SpringBoot 开发环境要求](./docs/start/springboot-system-requirements.md) -3. **[Spring Boot 版 Hello World & Spring Boot 项目结构分析](./docs/start/springboot-hello-world.md)** +## 重要知识点 ### 基础 -1. **[开发 RestFul Web 服务](./docs/basis/sringboot-restful-web-service.md)** -2. [RestController VS Controller](./docs/basis/RestControllerVSController.md) -3. [`@PostConstruct`和`@PreDestroy` 简单使用以及Java9+中的替代方案](./docs/basis/@PostConstruct与@PreDestroy.md) -4. **[Spring 如何优雅读取配置文件?](./docs/basis/read-config-properties.md)** -5. **[Spring Boot 异常处理](./docs/advanced/springboot-handle-exception.md)** -6. **[实际项目中我们是这样做异常处理的](./docs/advanced/springboot-handle-exception-plus.md)** -7. [使用 spring-boot-devtools 进行热部署](./docs/basis/spring-boot-devtools.md) (实际项目不太推荐热部署,影响效率) -8. **[ Spring Boot JPA 基础:常见操作解析](./docs/basis/springboot-jpa.md)** -9. **[JPA 中非常重要的连表查询就是这么简单](./docs/basis/springboot-jpa-lianbiao.md)** -10. [SpringBoot 实现过滤器](./docs/basis/springboot-filter.md) -11. [SpringBoot 实现拦截器](./docs/basis/springboot-interceptor.md) -12. [整合 SpringBoot+Mybatis](./docs/basis/springboot-mybatis.md) 、[SpirngBoot2.0+ 的 SpringBoot+Mybatis 多数据源配置](./docs/basis/springboot-mybatis-mutipledatasource.md) +1. [Spring Boot 介绍](./docs/start/springboot-introduction.md) +2. [第一个 Hello World](./docs/start/springboot-hello-world.md) +3. [第一个 RestFul Web 服务](./docs/basis/sringboot-restful-web-service.md) +4. [Spring 如何优雅读取配置文件?](./docs/basis/read-config-properties.md) +5. **异常处理** :[Spring Boot 异常处理的几种方式](./docs/advanced/springboot-handle-exception.md)、[Spring Boot 异常处理在实际项目中的应用](./docs/advanced/springboot-handle-exception-plus.md) +6. **JPA** : [ Spring Boot JPA 基础:常见操作解析](./docs/basis/springboot-jpa.md) 、 [JPA 中非常重要的连表查询就是这么简单](./docs/basis/springboot-jpa-lianbiao.md) +7. **拦截器和过滤器** :[SpringBoot 实现过滤器](./docs/basis/springboot-filter.md) 、[SpringBoot 实现拦截器](./docs/basis/springboot-interceptor.md) +8. **MyBatis** :[整合 SpringBoot+Mybatis](./docs/basis/springboot-mybatis.md) 、[SpirngBoot2.0+ 的 SpringBoot+Mybatis 多数据源配置](./docs/basis/springboot-mybatis-mutipledatasource.md) (TODO:早期文章,不建议阅读,待重构~) +9. [MyBatis-Plus 从入门到上手干事!](./docs/MyBatisPlus.md) +10. [SpringBoot 2.0+ 集成 Swagger 官方 Starter + knife4j 增强方案](./docs/basis/swagger.md) ### 进阶 -1. **[Bean映射工具之Apache BeanUtils VS Spring BeanUtils](./docs/advanced/Apache-BeanUtils-VS-SpringBean-Utils.md)** -2. [5种常见Bean映射工具的性能比对](./docs/advanced/Performance-of-Java-Mapping-Frameworks.md) -3. **[如何在 Spring/Spring Boot 中做参数校验?你需要了解的都在这里!](./docs/advanced/spring-bean-validation.md)** +1. Bean映射工具 :[Bean映射工具之Apache BeanUtils VS Spring BeanUtils](./docs/advanced/Apache-BeanUtils-VS-SpringBean-Utils.md) 、[5种常见Bean映射工具的性能比对](./docs/advanced/Performance-of-Java-Mapping-Frameworks.md) +3. [如何在 Spring/Spring Boot 中优雅地做参数校验?](./docs/spring-bean-validation.md) +3. [使用 PowerMockRunner 和 Mockito 编写单元测试用例](./docs/PowerMockRunnerAndMockito.md) 4. [5分钟搞懂如何在Spring Boot中Schedule Tasks](./docs/advanced/SpringBoot-ScheduleTasks.md) -5. **[新手也能看懂的 Spring Boot 异步编程指南](./docs/advanced/springboot-async.md)** -7. **[Kafka 入门+SpringBoot整合Kafka系列](https://github.com/Snailclimb/springboot-kafka)** -8. [超详细,新手都能看懂 !使用Spring Boot+Dubbo 搭建一个分布式服务](./docs/advanced/springboot-dubbo.md) -9. [从零入门 !Spring Security With JWT(含权限验证)](https://github.com/Snailclimb/spring-security-jwt-guide) +5. [新手也能看懂的 Spring Boot 异步编程指南](./docs/advanced/springboot-async.md) +6. [Kafka 入门+SpringBoot整合Kafka系列](https://github.com/Snailclimb/springboot-kafka) +7. [超详细,新手都能看懂 !使用Spring Boot+Dubbo 搭建一个分布式服务](./docs/advanced/springboot-dubbo.md) +8. [从零入门 !Spring Security With JWT(含权限验证)](https://github.com/Snailclimb/spring-security-jwt-guide) + +### 补充 -### 面试题 +1. [`@PostConstruct`和`@PreDestroy` 简单使用以及Java9+中的替代方案](./docs/basis/@PostConstruct与@PreDestroy.md) -- [几道简单的 SpringBoot面试题](./docs/interview/springboot-questions.md) +## 实战项目 + +1. [使用 Spring Boot搭建一个在线文件预览系统!支持ppt、doc等多种类型文件预览](./docs/projects/kkFileView-SpringBoot在线文件预览系统.md) +2. [ SpringBoot 前后端分离后台管理系统分析!分模块开发、RBAC权限控制...](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247495011&idx=1&sn=f574f5d75c3720d8b2a665d1d5234d28&chksm=cea1a2a8f9d62bbe9f13f5a030893fe3da6956c4be41471513e6247f74cba5a8df9941798b6e&token=212861022&lang=zh_CN#rd) +3. [一个基于Spring Cloud 的面试刷题系统。](./docs/projects/SpringCloud刷题系统.md) +4. [一个基于 Spring Boot 的在线考试系统](./docs/projects/一个基于SpringBoot的在线考试系统.md) ## 说明 1. 项目 logo 由 [logoly](https://logoly.pro/#/) 生成。 -2. 利用 docsify 生成文档部署在 Github pages: [docsify 官网介绍](https://docsify.js.org/#/) - -### 联系我 +2. 利用 docsify 生成文档部署在 Github Pages 和 Gitee Pages: [docsify 官网介绍](https://docsify.js.org/#/) -添加我的微信备注“Github”,回复关键字 **“加群”** 即可入群。 +### 优质原创PDF资源 -![个人微信](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/wechat3.jpeg) +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-2@main/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%B8%93%E4%B8%9A/image-20201027160348395.png) ### 公众号 如果大家想要实时关注我更新的文章以及分享的干货的话,可以关注我的公众号。 +**《Java面试突击》:** 由本文档衍生的专为面试而生的《Java面试突击》V2.0 PDF 版本[公众号](#公众号)后台回复 **"Java面试突击"** 即可免费领取! + **Java工程师必备学习资源:** 一些Java工程师常用学习资源公众号后台回复关键字 **“1”** 即可免费无套路获取。 ![我的公众号](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/167598cd2e17b8ec.png) diff --git a/docs/MyBatisPlus.md b/docs/MyBatisPlus.md new file mode 100644 index 0000000..afd4043 --- /dev/null +++ b/docs/MyBatisPlus.md @@ -0,0 +1,975 @@ +`MyBatis` 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射,而实际开发中,我们都会选择使用 `MyBatisPlus`,它是对 `MyBatis` 框架的进一步增强,能够极大地简化我们的持久层代码,下面就一起来看看 `MyBatisPlus` 中的一些奇淫巧技吧。 + +> 说明:本篇文章需要一定的 `MyBatis` 与 `MyBatisPlus` 基础 + +MyBatis-Plus 官网地址 : https://baomidou.com/ 。 + +## CRUD + +使用 `MyBatisPlus` 实现业务的增删改查非常地简单,一起来看看吧。 + +**1.首先新建一个 SpringBoot 工程,然后引入依赖:** + +```xml + + com.baomidou + mybatis-plus-boot-starter + 3.4.2 + + + mysql + mysql-connector-java + runtime + + + org.projectlombok + lombok + +``` + +**2.配置一下数据源:** + +```yaml +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + username: root + url: jdbc:mysql:///mybatisplus?serverTimezone=UTC + password: 123456 +``` + +**3.创建一下数据表:** + +```sql +CREATE DATABASE `mybatisplus`; + +USE `mybatisplus`; + +DROP TABLE IF EXISTS `tbl_employee`; + +CREATE TABLE `tbl_employee` ( + `id` bigint(20) NOT NULL, + `last_name` varchar(255) DEFAULT NULL, + `email` varchar(255) DEFAULT NULL, + `gender` char(1) DEFAULT NULL, + `age` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=gbk; + +insert into `tbl_employee`(`id`,`last_name`,`email`,`gender`,`age`) values (1,'jack','jack@qq.com','1',35),(2,'tom','tom@qq.com','1',30),(3,'jerry','jerry@qq.com','1',40); +``` + +**4.创建对应的实体类:** + +```java +@Data +public class Employee { + + private Long id; + private String lastName; + private String email; + private Integer age; +} +``` + +**4.编写 `Mapper` 接口:** + +```java +public interface EmployeeMapper extends BaseMapper { +} +``` + +我们只需继承 `MyBatisPlus` 提供的 `BaseMapper` 接口即可,现在我们就拥有了对 `Employee` 进行增删改查的 API,比如: + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private EmployeeMapper employeeMapper; + + @Test + void contextLoads() { + List employees = employeeMapper.selectList(null); + employees.forEach(System.out::println); + } +} +``` + +运行结果: + +```java +org.springframework.jdbc.BadSqlGrammarException: +### Error querying database. Cause: java.sql.SQLSyntaxErrorException: Table 'mybatisplus.employee' doesn't exist +``` + +程序报错了,原因是不存在 `employee` 表,这是因为我们的实体类名为 `Employee`,`MyBatisPlus` 默认是以类名作为表名进行操作的,可如果类名和表名不相同(实际开发中也确实可能不同),就需要在实体类中使用 `@TableName` 注解来声明表的名称: + +```java +@Data +@TableName("tbl_employee") // 声明表名称 +public class Employee { + + private Long id; + private String lastName; + private String email; + private Integer age; +} +``` + +重新执行测试代码,结果如下: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35) +Employee(id=2, lastName=tom, email=tom@qq.com, age=30) +Employee(id=3, lastName=jerry, email=jerry@qq.com, age=40) +``` + +`BaseMapper` 提供了常用的一些增删改查方法: + +![](https://img-blog.csdnimg.cn/20210519084059865.png) + +具体细节可以查阅其源码自行体会,注释都是中文的,非常容易理解。 + +在开发过程中,我们通常会使用 `Service` 层来调用 `Mapper` 层的方法,而 `MyBatisPlus` 也为我们提供了通用的 `Service`: + +```java +public interface EmployeeService extends IService { +} + +@Service +public class EmployeeServiceImpl extends ServiceImpl implements EmployeeService { +} +``` + +事实上,我们只需让 `EmployeeServiceImpl` 继承 `ServiceImpl` 即可获得 `Service` 层的方法,**那么为什么还需要实现 `EmployeeService` 接口呢?** + +这是因为实现 `EmployeeService` 接口能够更方便地对业务进行扩展,一些复杂场景下的数据处理,`MyBatisPlus` 提供的 `Service` 方法可能无法处理,此时我们就需要自己编写代码,这时候只需在 `EmployeeService` 中定义自己的方法,并在 `EmployeeServiceImpl` 中实现即可。 + +先来测试一下 `MyBatisPlus` 提供的 `Service` 方法: + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private EmployeeService employeeService; + + @Test + void contextLoads() { + List list = employeeService.list(); + list.forEach(System.out::println); + } +} +``` + +运行结果: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35) +Employee(id=2, lastName=tom, email=tom@qq.com, age=30) +Employee(id=3, lastName=jerry, email=jerry@qq.com, age=40) +``` + +接下来模拟一个自定义的场景,我们来编写自定义的操作方法,首先在 `EmployeeMapper` 中进行声明: + +```java +public interface EmployeeMapper extends BaseMapper { + + List selectAllByLastName(@Param("lastName") String lastName); +} +``` + +此时我们需要自己编写配置文件实现该方法,在 `resource` 目录下新建一个 `mapper` 文件夹,然后在该文件夹下创建 `EmployeeMapper.xml` 文件: + +```xml + + + + + + id, last_name, email, gender, age + + + + +``` + +`MyBatisPlus` 默认扫描的是类路径下的 `mapper` 目录,这可以从源码中得到体现: + +![](https://img-blog.csdnimg.cn/20210519084046472.png) + +所以我们直接将 `Mapper` 配置文件放在该目录下就没有任何问题,可如果不是这个目录,我们就需要进行配置,比如: + +```yaml +mybatis-plus: + mapper-locations: classpath:xml/*.xml +``` + +编写好 `Mapper` 接口后,我们就需要定义 `Service` 方法了: + +```java +public interface EmployeeService extends IService { + + List listAllByLastName(String lastName); +} + +@Service +public class EmployeeServiceImpl extends ServiceImpl implements EmployeeService { + + @Override + public List listAllByLastName(String lastName) { + return baseMapper.selectAllByLastName(lastName); + } +} +``` + +在 `EmployeeServiceImpl` 中我们无需将 `EmployeeMapper` 注入进来,而是使用 `BaseMapper`,查看 `ServiceImpl` 的源码: + +![](https://img-blog.csdnimg.cn/2021051908403249.png) + +可以看到它为我们注入了一个 `BaseMapper` 对象,而它是第一个泛型类型,也就是 `EmployeeMapper` 类型,所以我们可以直接使用这个 `baseMapper` 来调用 `Mapper` 中的方法,此时编写测试代码: + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private EmployeeService employeeService; + + @Test + void contextLoads() { + List list = employeeService.listAllByLastName("tom"); + list.forEach(System.out::println); + } +} +``` + +运行结果: + +```java +Employee(id=2, lastName=tom, email=tom@qq.com, age=30) +``` + +## ID 策略 + +在创建表的时候我故意没有设置主键的增长策略,现在我们来插入一条数据,看看主键是如何增长的: + +```java +@Test +void contextLoads() { + Employee employee = new Employee(); + employee.setLastName("lisa"); + employee.setEmail("lisa@qq.com"); + employee.setAge(20); + employeeService.save(employee); +} +``` + +插入成功后查询一下数据表: + +```sql +mysql> select * from tbl_employee; ++---------------------+-----------+--------------+--------+------+ +| id | last_name | email | gender | age | ++---------------------+-----------+--------------+--------+------+ +| 1 | jack | jack@qq.com | 1 | 35 | +| 2 | tom | tom@qq.com | 1 | 30 | +| 3 | jerry | jerry@qq.com | 1 | 40 | +| 1385934720849584129 | lisa | lisa@qq.com | NULL | 20 | ++---------------------+-----------+--------------+--------+------+ +4 rows in set (0.00 sec) +``` + +可以看到 id 是一串相当长的数字,这是什么意思呢?提前剧透一下,这其实是分布式 id,那又何为分布式 id 呢? + +我们知道,对于一个大型应用,其访问量是非常巨大的,就比如说一个网站每天都有人进行注册,注册的用户信息就需要存入数据表,随着日子一天天过去,数据表中的用户越来越多,此时数据库的查询速度就会受到影响,所以一般情况下,当数据量足够庞大时,数据都会做分库分表的处理。 + +然而,一旦分表,问题就产生了,很显然这些分表的数据都是属于同一张表的数据,只是因为数据量过大而分成若干张表,那么这几张表的主键 id 该怎么管理呢?每张表维护自己的 id?那数据将会有很多的 id 重复,这当然是不被允许的,其实,我们可以使用算法来生成一个绝对不会重复的 id,这样问题就迎刃而解了,事实上,分布式 id 的解决方案有很多: + +1. UUID +1. SnowFlake +1. TinyID +1. Uidgenerator +1. Leaf +6. Tinyid +7. ...... + +以 UUID 为例,它生成的是一串由数字和字母组成的字符串,显然并不适合作为数据表的 id,而且 id 保持递增有序会加快表的查询效率,基于此,`MyBatisPlus` 使用的就是 `SnowFlake`(雪花算法)。 + +`Snowflake` 是 Twitter 开源的分布式 ID 生成算法。`Snowflake` 由 64 bit 的二进制数字组成,这 64bit 的二进制被分成了几部分,每一部分存储的数据都有特定的含义: + +- **第 0 位**: 符号位(标识正负),始终为 0,没有用,不用管。 +- **第 1~41 位** :一共 41 位,用来表示时间戳,单位是毫秒,可以支撑 2 ^41 毫秒(约 69 年) +- **第 42~52 位** :一共 10 位,一般来说,前 5 位表示机房 ID,后 5 位表示机器 ID(实际项目中可以根据实际情况调整)。这样就可以区分不同集群/机房的节点。 +- **第 53~64 位** :一共 12 位,用来表示序列号。 序列号为自增值,代表单台机器每毫秒能够产生的最大 ID 数(2^12 = 4096),也就是说单台机器每毫秒最多可以生成 4096 个 唯一 ID。 + +![](https://oscimg.oschina.net/oscnet/up-a7e54a77b5ab1d9fa16d5ae3a3c50c5aee9.png) + +这也就是为什么插入数据后新的数据 id 是一长串数字的原因了,我们可以在实体类中使用 `@TableId` 来设置主键的策略: + +```java +@Data +@TableName("tbl_employee") +public class Employee { + + @TableId(type = IdType.AUTO) // 设置主键策略 + private Long id; + private String lastName; + private String email; + private Integer age; +} +``` + +`MyBatisPlus` 提供了几种主键的策略: +![](https://img-blog.csdnimg.cn/20210519084011745.png) +其中 `AUTO` 表示数据库自增策略,该策略下需要数据库实现主键的自增(auto_increment),`ASSIGN_ID` 是雪花算法,默认使用的是该策略,`ASSIGN_UUID` 是 UUID 策略,一般不会使用该策略。 + +这里多说一点, 当实体类的主键名为 id,并且数据表的主键名也为 id 时,此时 `MyBatisPlus` 会自动判定该属性为主键 id,倘若名字不是 id 时,就需要标注 `@TableId` 注解,若是实体类中主键名与数据表的主键名不一致,则可以进行声明: + +```java +@TableId(value = "uid",type = IdType.AUTO) // 设置主键策略 +private Long id; +``` + +还可以在配置文件中配置全局的主键策略: + +```yaml +mybatis-plus: + global-config: + db-config: + id-type: auto +``` + +这样能够避免在每个实体类中重复设置主键策略。 + +## 属性自动填充 + +翻阅《阿里巴巴Java开发手册》,在第 5 章 MySQL 数据库可以看到这样一条规范: +![](https://img-blog.csdnimg.cn/20210426214821389.png) +对于一张数据表,它必须具备三个字段: + +- `id` : 唯一ID +- `gmt_create` : 保存的是当前数据创建的时间 +- `gmt_modified` : 保存的是更新时间 + +我们改造一下数据表: + +```sql +alter table tbl_employee add column gmt_create datetime not null; +alter table tbl_employee add column gmt_modified datetime not null; +``` + +然后改造一下实体类: + +```java +@Data +@TableName("tbl_employee") +public class Employee { + + @TableId(type = IdType.AUTO) // 设置主键策略 + private Long id; + private String lastName; + private String email; + private Integer age; + private LocalDateTime gmtCreate; + private LocalDateTime gmtModified; +} +``` + +此时我们在插入数据和更新数据的时候就需要手动去维护这两个属性: + +```java +@Test +void contextLoads() { + Employee employee = new Employee(); + employee.setLastName("lisa"); + employee.setEmail("lisa@qq.com"); + employee.setAge(20); + // 设置创建时间 + employee.setGmtCreate(LocalDateTime.now()); + employee.setGmtModified(LocalDateTime.now()); + employeeService.save(employee); +} + +@Test +void contextLoads() { + Employee employee = new Employee(); + employee.setId(1385934720849584130L); + employee.setAge(50); + // 设置创建时间 + employee.setGmtModified(LocalDateTime.now()); + employeeService.updateById(employee); +} +``` + +每次都需要维护这两个属性未免过于麻烦,好在 `MyBatisPlus` 提供了字段自动填充功能来帮助我们进行管理,需要使用到的是 `@TableField` 注解: + +```java +@Data +@TableName("tbl_employee") +public class Employee { + + @TableId(type = IdType.AUTO) + private Long id; + private String lastName; + private String email; + private Integer age; + @TableField(fill = FieldFill.INSERT) // 插入的时候自动填充 + private LocalDateTime gmtCreate; + @TableField(fill = FieldFill.INSERT_UPDATE) // 插入和更新的时候自动填充 + private LocalDateTime gmtModified; +} +``` + +然后编写一个类实现 MetaObjectHandler 接口: + +```java +@Component +@Slf4j +public class MyMetaObjectHandler implements MetaObjectHandler { + + /** + * 实现插入时的自动填充 + * @param metaObject + */ + @Override + public void insertFill(MetaObject metaObject) { + log.info("insert开始属性填充"); + this.strictInsertFill(metaObject,"gmtCreate", LocalDateTime.class,LocalDateTime.now()); + this.strictInsertFill(metaObject,"gmtModified", LocalDateTime.class,LocalDateTime.now()); + } + + /** + * 实现更新时的自动填充 + * @param metaObject + */ + @Override + public void updateFill(MetaObject metaObject) { + log.info("update开始属性填充"); + this.strictInsertFill(metaObject,"gmtModified", LocalDateTime.class,LocalDateTime.now()); + } +} +``` + +该接口中有两个未实现的方法,分别为插入和更新时的填充方法,在方法中调用 `strictInsertFill()` 方法 即可实现属性的填充,它需要四个参数: + +1. `metaObject`:元对象,就是方法的入参 +1. `fieldName`:为哪个属性进行自动填充 +1. `fieldType`:属性的类型 +1. `fieldVal`:需要填充的属性值 + +此时在插入和更新数据之前,这两个方法会先被执行,以实现属性的自动填充,通过日志我们可以进行验证: + +```java +@Test +void contextLoads() { + Employee employee = new Employee(); + employee.setId(1385934720849584130L); + employee.setAge(15); + employeeService.updateById(employee); +} +``` + +运行结果: + +```java +INFO 15584 --- [ main] c.w.m.handler.MyMetaObjectHandler : update开始属性填充 +2021-04-24 21:32:19.788 INFO 15584 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... +2021-04-24 21:32:21.244 INFO 15584 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. +``` + +属性填充其实可以进行一些优化,考虑一些特殊情况,对于一些不存在的属性,就不需要进行属性填充,对于一些设置了值的属性,也不需要进行属性填充,这样可以提高程序的整体运行效率: + +```java +@Component +@Slf4j +public class MyMetaObjectHandler implements MetaObjectHandler { + + @Override + public void insertFill(MetaObject metaObject) { + boolean hasGmtCreate = metaObject.hasSetter("gmtCreate"); + boolean hasGmtModified = metaObject.hasSetter("gmtModified"); + if (hasGmtCreate) { + Object gmtCreate = this.getFieldValByName("gmtCreate", metaObject); + if (gmtCreate == null) { + this.strictInsertFill(metaObject, "gmtCreate", LocalDateTime.class, LocalDateTime.now()); + } + } + if (hasGmtModified) { + Object gmtModified = this.getFieldValByName("gmtModified", metaObject); + if (gmtModified == null) { + this.strictInsertFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now()); + } + } + } + + @Override + public void updateFill(MetaObject metaObject) { + boolean hasGmtModified = metaObject.hasSetter("gmtModified"); + if (hasGmtModified) { + Object gmtModified = this.getFieldValByName("gmtModified", metaObject); + if (gmtModified == null) { + this.strictInsertFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now()); + } + } + } +} +``` + +## 逻辑删除 + +逻辑删除对应的是物理删除,分别介绍一下这两个概念: + +1. **物理删除** :指的是真正的删除,即:当执行删除操作时,将数据表中的数据进行删除,之后将无法再查询到该数据 +1. **逻辑删除** :并不是真正意义上的删除,只是对于用户不可见了,它仍然存在与数据表中 + +在这个数据为王的时代,数据就是财富,所以一般并不会有哪个系统在删除某些重要数据时真正删掉了数据,通常都是在数据库中建立一个状态列,让其默认为 0,当为 0 时,用户可见;当执行了删除操作,就将状态列改为 1,此时用户不可见,但数据还是在表中的。 + +![](https://img-blog.csdnimg.cn/20210426215107210.png) + +按照《阿里巴巴Java开发手册》第 5 章 MySQL 数据库相关的建议,我们来为数据表新增一个`is_deleted` 字段: + +```sql +alter table tbl_employee add column is_deleted tinyint not null; +``` + +在实体类中也要添加这一属性: + +```java +@Data +@TableName("tbl_employee") +public class Employee { + + @TableId(type = IdType.AUTO) + private Long id; + private String lastName; + private String email; + private Integer age; + @TableField(fill = FieldFill.INSERT) + private LocalDateTime gmtCreate; + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime gmtModified; + /** + * 逻辑删除属性 + */ + @TableLogic + @TableField("is_deleted") + private Boolean deleted; +} +``` + +![](https://img-blog.csdnimg.cn/2021042621530162.png) + +还是参照《阿里巴巴Java开发手册》第 5 章 MySQL 数据库相关的建议,对于布尔类型变量,不能加 is 前缀,所以我们的属性被命名为 `deleted`,但此时就无法与数据表的字段进行对应了,所以我们需要使用 `@TableField` 注解来声明一下数据表的字段名,而 `@TableLogin` 注解用于设置逻辑删除属性;此时我们执行删除操作: + +```java +@Test +void contextLoads() { + employeeService.removeById(3); +} +``` + +查询数据表: + +```sql +mysql> select * from tbl_employee; ++---------------------+-----------+--------------+--------+------+---------------------+---------------------+------------+ +| id | last_name | email | gender | age | gmt_create | gmt_modified | is_deleted | ++---------------------+-----------+--------------+--------+------+---------------------+---------------------+------------+ +| 1 | jack | jack@qq.com | 1 | 35 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 0 | +| 2 | tom | tom@qq.com | 1 | 30 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 0 | +| 3 | jerry | jerry@qq.com | 1 | 40 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 1 | +| 1385934720849584129 | lisa | lisa@qq.com | NULL | 20 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 0 | +| 1385934720849584130 | lisa | lisa@qq.com | NULL | 15 | 2021-04-24 21:14:18 | 2021-04-24 21:32:19 | 0 | ++---------------------+-----------+--------------+--------+------+---------------------+---------------------+------------+ +5 rows in set (0.00 sec) +``` + +可以看到数据并没有被删除,只是 `is_deleted` 字段的属性值被更新成了 1,此时我们再来执行查询操作: + +```java +@Test +void contextLoads() { + List list = employeeService.list(); + list.forEach(System.out::println); +} +``` + +执行结果: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=false) +Employee(id=2, lastName=tom, email=tom@qq.com, age=30, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=false) +Employee(id=1385934720849584129, lastName=lisa, email=lisa@qq.com, age=20, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=false) +Employee(id=1385934720849584130, lastName=lisa, email=lisa@qq.com, age=15, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:32:19, deleted=false) +``` + +会发现第三条数据并没有被查询出来,它是如何实现的呢?我们可以输出 `MyBatisPlus` 生成的 SQL 来分析一下,在配置文件中进行配置: + +```yaml +mybatis-plus: + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 输出SQL日志 +``` + +运行结果: + +```java +==> Preparing: SELECT id,last_name,email,age,gmt_create,gmt_modified,is_deleted AS deleted FROM tbl_employee WHERE is_deleted=0 +==> Parameters: +<== Columns: id, last_name, email, age, gmt_create, gmt_modified, deleted +<== Row: 1, jack, jack@qq.com, 35, 2021-04-24 21:14:18, 2021-04-24 21:14:18, 0 +<== Row: 2, tom, tom@qq.com, 30, 2021-04-24 21:14:18, 2021-04-24 21:14:18, 0 +<== Row: 1385934720849584129, lisa, lisa@qq.com, 20, 2021-04-24 21:14:18, 2021-04-24 21:14:18, 0 +<== Row: 1385934720849584130, lisa, lisa@qq.com, 15, 2021-04-24 21:14:18, 2021-04-24 21:32:19, 0 +<== Total: 4 +``` + +原来它在查询时携带了一个条件: `is_deleted=0` ,这也说明了 `MyBatisPlus` 默认 0 为不删除,1 为删除。 +若是你想修改这个规定,比如设置-1 为删除,1 为不删除,也可以进行配置: + +```yaml +mybatis-plus: + global-config: + db-config: + id-type: auto + logic-delete-field: deleted # 逻辑删除属性名 + logic-delete-value: -1 # 删除值 + logic-not-delete-value: 1 # 不删除值 +``` + +但建议使用默认的配置,阿里巴巴开发手册也规定 1 表示删除,0 表示未删除。 + +## 分页插件 + +对于分页功能,`MyBatisPlus` 提供了分页插件,只需要进行简单的配置即可实现: + +```java +@Configuration +public class MyBatisConfig { + + /** + * 注册分页插件 + * @return + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + return interceptor; + } +} +``` + +接下来我们就可以使用分页插件提供的功能了: + +```java +@Test +void contextLoads() { + Page page = new Page<>(1,2); + employeeService.page(page, null); + List employeeList = page.getRecords(); + employeeList.forEach(System.out::println); + System.out.println("获取总条数:" + page.getTotal()); + System.out.println("获取当前页码:" + page.getCurrent()); + System.out.println("获取总页码:" + page.getPages()); + System.out.println("获取每页显示的数据条数:" + page.getSize()); + System.out.println("是否有上一页:" + page.hasPrevious()); + System.out.println("是否有下一页:" + page.hasNext()); +} +``` + +其中的 `Page` 对象用于指定分页查询的规则,这里表示按每页两条数据进行分页,并查询第一页的内容,运行结果: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=0) +Employee(id=2, lastName=tom, email=tom@qq.com, age=30, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=0) +获取总条数:4 +获取当前页码:1 +获取总页码:2 +获取每页显示的数据条数:2 +是否有上一页:false +是否有下一页:true +``` + +倘若在分页过程中需要限定一些条件,我们就需要构建 QueryWrapper 来实现: + +```java +@Test +void contextLoads() { + Page page = new Page<>(1, 2); + employeeService.page(page, new QueryWrapper() + .between("age", 20, 50) + .eq("gender", 1)); + List employeeList = page.getRecords(); + employeeList.forEach(System.out::println); +} +``` + +此时分页的数据就应该是年龄在 20~50 岁之间,且 gender 值为 1 的员工信息,然后再对这些数据进行分页。 + +## 乐观锁 + +当程序中出现并发访问时,就需要保证数据的一致性。以商品系统为例,现在有两个管理员均想对同一件售价为 100 元的商品进行修改,A 管理员正准备将商品售价改为 150 元,但此时出现了网络问题,导致 A 管理员的操作陷入了等待状态;此时 B 管理员也进行修改,将商品售价改为了 200 元,修改完成后 B 管理员退出了系统,此时 A 管理员的操作也生效了,这样便使得 A 管理员的操作直接覆盖了 B 管理员的操作,B 管理员后续再进行查询时会发现商品售价变为了 150 元,这样的情况是绝对不允许发生的。 + +要想解决这一问题,可以给数据表加锁,常见的方式有两种: + +1. 乐观锁 +1. 悲观锁 + +悲观锁认为并发情况一定会发生,所以在某条数据被修改时,为了避免其它人修改,会直接对数据表进行加锁,它依靠的是数据库本身提供的锁机制(表锁、行锁、读锁、写锁)。 + +而乐观锁则相反,它认为数据产生冲突的情况一般不会发生,所以在修改数据的时候并不会对数据表进行加锁的操作,而是在提交数据时进行校验,判断提交上来的数据是否会发生冲突,如果发生冲突,则提示用户重新进行操作,一般的实现方式为 `设置版本号字段` 。 + +就以商品售价为例,在该表中设置一个版本号字段,让其初始为 1,此时 A 管理员和 B 管理员同时需要修改售价,它们会先读取到数据表中的内容,此时两个管理员读取到的版本号都为 1,此时 B 管理员的操作先生效了,它就会将当前数据表中对应数据的版本号与最开始读取到的版本号作一个比对,发现没有变化,于是修改就生效了,此时版本号加 1。 + +而 A 管理员马上也提交了修改操作,但是此时的版本号为 2,与最开始读取到的版本号并不对应,这就说明数据发生了冲突,此时应该提示 A 管理员操作失败,并让 A 管理员重新查询一次数据。 + +![](https://img-blog.csdnimg.cn/20210426221408623.png) + +乐观锁的优势在于采取了更加宽松的加锁机制,能够提高程序的吞吐量,适用于读操作多的场景。 + +那么接下来我们就来模拟这一过程。 + +**1.创建一张新的数据表:** + +```sql +create table shop( + id bigint(20) not null auto_increment, + name varchar(30) not null, + price int(11) default 0, + version int(11) default 1, + primary key(id) +); + +insert into shop(id,name,price) values(1,'笔记本电脑',8000); +``` + +**2.创建实体类:** + +```java +@Data +public class Shop { + + private Long id; + private String name; + private Integer price; + private Integer version; +} +``` + +**3.创建对应的 `Mapper` 接口:** + +```java +public interface ShopMapper extends BaseMapper { +} +``` + +**4.编写测试代码:** + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private ShopMapper shopMapper; + + /** + * 模拟并发场景 + */ + @Test + void contextLoads() { + // A、B管理员读取数据 + Shop A = shopMapper.selectById(1L); + Shop B = shopMapper.selectById(1L); + // B管理员先修改 + B.setPrice(9000); + int result = shopMapper.updateById(B); + if (result == 1) { + System.out.println("B管理员修改成功!"); + } else { + System.out.println("B管理员修改失败!"); + } + // A管理员后修改 + A.setPrice(8500); + int result2 = shopMapper.updateById(A); + if (result2 == 1) { + System.out.println("A管理员修改成功!"); + } else { + System.out.println("A管理员修改失败!"); + } + // 最后查询 + System.out.println(shopMapper.selectById(1L)); + } +} +``` + +执行结果: + +```java +B管理员修改成功! +A管理员修改成功! +Shop(id=1, name=笔记本电脑, price=8500, version=1) +``` + +**问题出现了,B 管理员的操作被 A 管理员覆盖,那么该如何解决这一问题呢?** + +其实 `MyBatisPlus` 已经提供了乐观锁机制,只需要在实体类中使用 `@Version` 声明版本号属性: + +```java +@Data +public class Shop { + + private Long id; + private String name; + private Integer price; + @Version // 声明版本号属性 + private Integer version; +} +``` + +然后注册乐观锁插件: + +```java +@Configuration +public class MyBatisConfig { + + /** + * 注册插件 + * @return + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + // 分页插件 + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + // 乐观锁插件 + interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); + return interceptor; + } +} +``` + +重新执行测试代码,结果如下: + +```java +B管理员修改成功! +A管理员修改失败! +Shop(id=1, name=笔记本电脑, price=9000, version=2) +``` + +此时 A 管理员的修改就失败了,它需要重新读取最新的数据才能再次进行修改。 + +## 条件构造器 + +在分页插件中我们简单地使用了一下条件构造器(`Wrapper`),下面我们来详细了解一下。 +先来看看 `Wrapper` 的继承体系: +![](https://img-blog.csdnimg.cn/20210519083944315.png) +分别介绍一下它们的作用: + +- `Wrapper`:条件构造器抽象类,最顶端的父类 + - `AbstractWrapper`:查询条件封装抽象类,生成 SQL 的 where 条件 + - `QueryWrapper`:用于对象封装 + - `UpdateWrapper`:用于条件封装 + - `AbstractLambdaWrapper`:Lambda 语法使用 Wrapper + - `LambdaQueryWrapper`:用于对象封装,使用 Lambda 语法 + - `LambdaUpdateWrapper`:用于条件封装,使用 Lambda 语法 + +通常我们使用的都是 `QueryWrapper` 和 `UpdateWrapper`,若是想使用 Lambda 语法来编写,也可以使用 `LambdaQueryWrapper` 和 `LambdaUpdateWrapper`,通过这些条件构造器,我们能够很方便地来实现一些复杂的筛选操作,比如: + +```java +@SpringBootTest +@MapperScan("com.wwj.mybatisplusdemo.mapper") +class MybatisplusDemoApplicationTests { + + @Autowired + private EmployeeMapper employeeMapper; + + @Test + void contextLoads() { + // 查询名字中包含'j',年龄大于20岁,邮箱不为空的员工信息 + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.like("last_name", "j"); + wrapper.gt("age", 20); + wrapper.isNotNull("email"); + List list = employeeMapper.selectList(wrapper); + list.forEach(System.out::println); + } +} +``` + +运行结果: + +```java +Employee(id=1, lastName=jack, email=jack@qq.com, age=35, gmtCreate=2021-04-24T21:14:18, gmtModified=2021-04-24T21:14:18, deleted=0) +``` + +条件构造器提供了丰富的条件方法帮助我们进行条件的构造,比如 `like` 方法会为我们建立模糊查询,查看一下控制台输出的 SQL: + +```sql +==> Preparing: SELECT id,last_name,email,age,gmt_create,gmt_modified,is_deleted AS deleted FROM tbl_employee WHERE is_deleted=0 AND (last_name LIKE ? AND age > ? AND email IS NOT NULL) +==> Parameters: %j%(String), 20(Integer) +``` + +可以看到它是对 `j` 的前后都加上了 `%` ,若是只想查询以 `j` 开头的名字,则可以使用 `likeRight` 方法,若是想查询以 `j` 结尾的名字,,则使用 `likeLeft` 方法。 + +年龄的比较也是如此, `gt` 是大于指定值,若是小于则调用 `lt` ,大于等于调用 `ge` ,小于等于调用 `le` ,不等于调用 `ne` ,还可以使用 `between` 方法实现这一过程,相关的其它方法都可以查阅源码进行学习。 + +因为这些方法返回的其实都是自身实例,所以可使用链式编程: + +```java +@Test +void contextLoads() { + // 查询名字中包含'j',年龄大于20岁,邮箱不为空的员工信息 + QueryWrapper wrapper = new QueryWrapper() + .likeLeft("last_name", "j") + .gt("age", 20) + .isNotNull("email"); + List list = employeeMapper.selectList(wrapper); + list.forEach(System.out::println); +} +``` + +也可以使用 `LambdaQueryWrapper` 实现: + +```java +@Test +void contextLoads() { + // 查询名字中包含'j',年龄大于20岁,邮箱不为空的员工信息 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .like(Employee::getLastName,"j") + .gt(Employee::getAge,20) + .isNotNull(Employee::getEmail); + List list = employeeMapper.selectList(wrapper); + list.forEach(System.out::println); +} +``` + +这种方式的好处在于对字段的设置不是硬编码,而是采用方法引用的形式,效果与 `QueryWrapper` 是一样的。 + +`UpdateWrapper` 与 `QueryWrapper` 不同,它的作用是封装更新内容的,比如: + +```java +@Test +void contextLoads() { + UpdateWrapper wrapper = new UpdateWrapper() + .set("age", 50) + .set("email", "emp@163.com") + .like("last_name", "j") + .gt("age", 20); + employeeMapper.update(null, wrapper); +} +``` + +将名字中包含 `j` 且年龄大于 20 岁的员工年龄改为 50,邮箱改为 emp@163.com,`UpdateWrapper` 不仅能够封装更新内容,也能作为查询条件,所以在更新数据时可以直接构造一个 `UpdateWrapper` 来设置更新内容和条件。 \ No newline at end of file diff --git a/docs/PowerMockRunnerAndMockito.md b/docs/PowerMockRunnerAndMockito.md new file mode 100644 index 0000000..469e075 --- /dev/null +++ b/docs/PowerMockRunnerAndMockito.md @@ -0,0 +1,161 @@ +单元测试可以提高测试开发的效率,减少代码错误率,提高代码健壮性,提高代码质量。在 Spring 框架中常用的两种测试框架:`PowerMockRunner` 和 `SpringRunner` 两个单元测试,鉴于 `SpringRunner` 启动的一系列依赖和数据连接的问题,推荐使用 `PowerMockRunner`,这样能有效的提高测试的效率,并且其提供的 API 能覆盖的场景广泛,使用方便,可谓是 Java 单元测试之模拟利器。 + +## 1. PowerMock 是什么? + +`PowerMock` 是一个 Java 模拟框架,可用于解决通常认为很难甚至无法测试的测试问题。使用 `PowerMock`,可以模拟静态方法,删除静态初始化程序,允许模拟而不依赖于注入,等等。`PowerMock` 通过在执行测试时在运行时修改字节码来完成这些技巧。`PowerMock` 还包含一些实用程序,可让您更轻松地访问对象的内部状态。 + +举个例子,你在使用 `Junit` 进行单元测试时,并不想让测试数据进入数据库,怎么办?这个时候就可以使用 `PowerMock`,拦截数据库操作,并模拟返回参数。 + +## 2. PowerMock 包引入 + +```xml + + + org.powermock + powermock-core + 2.0.2 + test + + + org.mockito + mockito-core + 2.23.0 + + + org.powermock + powermock-module-junit4 + 2.0.4 + test + + + org.powermock + powermock-api-mockito2 + 2.0.2 + test + + + com.github.jsonzou + jmockdata + 4.3.0 + +``` + +## 3. 重要注解说明 + +```java +@RunWith(PowerMockRunner.class) // 告诉JUnit使用PowerMockRunner进行测试 +@PrepareForTest({RandomUtil.class}) // 所有需要测试的类列在此处,适用于模拟final类或有final, private, static, native方法的类 +@PowerMockIgnore("javax.management.*") //为了解决使用powermock后,提示classloader错误 +``` + +## 4. 使用示例 + +### 4.1 模拟接口返回 + +首先对接口进行 mock,然后录制相关行为 + +```java +InterfaceToMock mock = Powermockito.mock(InterfaceToMock.class) +Powermockito.when(mock.method(Params…)).thenReturn(value) +Powermockito.when(mock.method(Params..)).thenThrow(Exception) +``` + +### 4.2 设置对象的 private 属性 + +需要使用 `Whitebox` 向 class 或者对象中赋值。 + +如我们已经对接口尽心了 mock,现在需要将此 mock 加入到对象中,可以采用如下方法: + +```java +Whitebox.setInternalState(Object object, String fieldname, Object… value); +``` + +其中 object 为需要设置属性的静态类或对象。 + +### 4.3 模拟构造函数 + +对于模拟构造函数,也即当出现 `new InstanceClass()` 时可以将此构造函数拦截并替换结果为我们需要的 mock 对象。 + +注意:使用时需要加入标记: + +```java +@RunWith(PowerMockRunner.class) +@PrepareForTest({ InstanceClass.class }) +@PowerMockIgnore("javax.management.\*") + +Powermockito.whenNew(InstanceClass.class).thenReturn(Object value) +``` + +##### 4.4 模拟静态方法 + +模拟静态方法类似于模拟构造函数,也需要加入注释标记。 + +```java +@RunWith(PowerMockRunner.class) +@PrepareForTest({ StaticClassToMock.class }) +@PowerMockIgnore("javax.management.\*") + +Powermockito.mockStatic(StaticClassToMock.class); +Powermockito.when(StaticClassToMock.method(Object.. params)).thenReturn(Object value) +``` + +##### 4.5 模拟 final 方法 + +Final 方法的模拟类似于模拟静态方法。 + +```java +@RunWith(PowerMockRunner.class) +@PrepareForTest({ FinalClassToMock.class }) +@PowerMockIgnore("javax.management.\*") + +Powermockito.mockStatic(FinalClassToMock.class); +Powermockito.when(StaticClassToMock.method(Object.. params)).thenReturn(Object value) +``` + +### 4.6 模拟静态类 + +模拟静态类类似于模拟静态方法。 + +### 4.7 使用 spy 方法避免执行被测类中的成员函数 + +如被测试类为:TargetClass,想要屏蔽的方法为 targetMethod. + +```java +1) PowerMockito.spy(TargetClass.class); + +2) Powemockito.when(TargetClass.targetMethod()).doReturn() + +3) 注意加入 + +@RunWith(PowerMockRunner.class) +@PrepareForTest(DisplayMoRelationBuilder.class) +@PowerMockIgnore("javax.management.*") +``` + +### 4.8 参数匹配器 + +有时我们在处理 `doMethod(Param param)` 时,不想进行精确匹配,这时可以使用 `Mockito` 提供的模糊匹配方式。 + +如:`Mockito.anyInt()`,`Mockito.anyString()` + +### 4.9 处理 public void 型的静态方法 + +```java +Powermockito.doNothing.when(T class2mock, String method, … params> +``` + +## 5. 单元测试用例可选清单 + +输入数据验证:这些检查通常可以对输入到应用程序系统中的数据采用。 + +- 必传项测试 +- 唯一字段值测试 +- 空值测试 +- 字段只接受允许的字符 +- 负值测试 +- 字段限于字段长度规范 +- 不可能的值 +- 垃圾值测试 +- 检查字段之间的依赖性 +- 等效类划分和边界条件测试 +- 错误和异常处理测试单元测试可以提高测试开发的效率,减少代码错误率,提高代码健壮性,提高代码质量。在 Spring 框架中常用的两种测试框架:PowerMockRunner 和 SpringRunner 两个单元测试,鉴于 SpringRunner 启动的一系列依赖和数据连接的问题,推荐使用 PowerMockRunner,这样能有效的提高测试的效率,并且其提供的 API 能覆盖的场景广泛,使用方便,可谓是 Java 单元测试之模拟利器。 \ No newline at end of file diff --git a/docs/advanced/SpringBoot-ScheduleTasks.md b/docs/advanced/SpringBoot-ScheduleTasks.md index 135eb2d..a443545 100644 --- a/docs/advanced/SpringBoot-ScheduleTasks.md +++ b/docs/advanced/SpringBoot-ScheduleTasks.md @@ -12,7 +12,7 @@ > Cron 表达式: 主要用于定时作业(定时任务)系统定义执行时间或执行频率的表达式,非常厉害,你可以通过 Cron 表达式进行设置定时任务每天或者每个月什么时候执行等等操作。 > -> 推荐一个在线Cron表达式生成器:[http://cron.qqe2.com/](http://cron.qqe2.com/) +> 推荐一个在线Cron表达式生成器: [https://crontab.guru/](https://crontab.guru/) ```java import org.slf4j.Logger; diff --git a/docs/advanced/spring-bean-validation.md b/docs/advanced/spring-bean-validation.md deleted file mode 100644 index 902220a..0000000 --- a/docs/advanced/spring-bean-validation.md +++ /dev/null @@ -1,540 +0,0 @@ -**数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。** - -本文结合自己在项目中的实际使用经验,可以说**文章介绍的内容很实用,不了解的朋友可以学习一下,后面可以立马实践到项目上去。** - -下面我会通过实例程序演示如何在 Java 程序中尤其是 Spring 程序中优雅地的进行参数验证。 - -## 基础设施搭建 - -### 相关依赖 - -如果开发普通 Java 程序的的话,你需要可能需要像下面这样依赖: - -```xml - - org.hibernate.validator - hibernate-validator - 6.0.9.Final - - - javax.el - javax.el-api - 3.0.0 - - - org.glassfish.web - javax.el - 2.2.6 - -``` - -使用 Spring Boot 程序的话只需要`spring-boot-starter-web` 就够了,它的子依赖包含了我们所需要的东西。除了这个依赖,下面的演示还用到了 lombok ,所以不要忘记添加上相关依赖。 - -```xml - - - org.springframework.boot - spring-boot-starter-web - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - -``` - -### 实体类 - -下面这个是示例用到的实体类。 - -```java -@Data -@AllArgsConstructor -@NoArgsConstructor -public class Person { - - @NotNull(message = "classId 不能为空") - private String classId; - - @Size(max = 33) - @NotNull(message = "name 不能为空") - private String name; - - @Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可选范围") - @NotNull(message = "sex 不能为空") - private String sex; - - @Email(message = "email 格式不正确") - @NotNull(message = "email 不能为空") - private String email; - -} -``` - -> 正则表达式说明: -> -> ``` -> - ^string : 匹配以 string 开头的字符串 -> - string$ :匹配以 string 结尾的字符串 -> - ^string$ :精确匹配 string 字符串 -> - ((^Man$|^Woman$|^UGM$)) : 值只能在 Man,Woman,UGM 这三个值中选择 -> ``` - -下面这部分校验注解说明内容参考自:https://www.cnkirito.moe/spring-validation/ ,感谢@[徐靖峰](https://github.com/lexburner)。 - -**JSR提供的校验注解**: - - -- `@Null` 被注释的元素必须为 null -- `@NotNull` 被注释的元素必须不为 null -- `@AssertTrue` 被注释的元素必须为 true -- `@AssertFalse` 被注释的元素必须为 false -- `@Min(value) ` 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 -- `@Max(value) ` 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 -- `@DecimalMin(value) ` 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 -- `@DecimalMax(value)` 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 -- `@Size(max=, min=) ` 被注释的元素的大小必须在指定的范围内 -- `@Digits (integer, fraction) ` 被注释的元素必须是一个数字,其值必须在可接受的范围内 -- `@Past ` 被注释的元素必须是一个过去的日期 -- `@Future` 被注释的元素必须是一个将来的日期 -- `@Pattern(regex=,flag=) ` 被注释的元素必须符合指定的正则表达式 - - -**Hibernate Validator提供的校验注解**: - - -- `@NotBlank(message =) ` 验证字符串非null,且长度必须大于0 -- `@Email` 被注释的元素必须是电子邮箱地址 -- `@Length(min=,max=) ` 被注释的字符串的大小必须在指定的范围内 -- `@NotEmpty ` 被注释的字符串的必须非空 -- `@Range(min=,max=,message=)` 被注释的元素必须在合适的范围内 - -## 验证Controller的输入 - -### 验证请求体(RequestBody) - -**Controller:** - -我们在需要验证的参数上加上了`@Valid`注解,如果验证失败,它将抛出`MethodArgumentNotValidException`。默认情况下,Spring会将此异常转换为HTTP Status 400(错误请求)。 - -```java - -@RestController -@RequestMapping("/api") -public class PersonController { - - @PostMapping("/person") - public ResponseEntity getPerson(@RequestBody @Valid Person person) { - return ResponseEntity.ok().body(person); - } -} -``` - -**ExceptionHandler:** - -自定义异常处理器可以帮助我们捕获异常,并进行一些简单的处理。如果对于下面的处理异常的代码不太理解的话,可以查看这篇文章 [《SpringBoot 处理异常的几种常见姿势》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247485568&idx=2&sn=c5ba880fd0c5d82e39531fa42cb036ac&chksm=cea2474bf9d5ce5dcbc6a5f6580198fdce4bc92ef577579183a729cb5d1430e4994720d59b34&token=1924773784&lang=zh_CN#rd)。 - -```java -@ControllerAdvice(assignableTypes = {PersonController.class}) -public class GlobalExceptionHandler { - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity> handleValidationExceptions( - MethodArgumentNotValidException ex) { - Map errors = new HashMap<>(); - ex.getBindingResult().getAllErrors().forEach((error) -> { - String fieldName = ((FieldError) error).getField(); - String errorMessage = error.getDefaultMessage(); - errors.put(fieldName, errorMessage); - }); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); - } -} -``` - -**通过测试验证:** - -下面我通过 MockMvc 模拟请求 Controller 的方式来验证是否生效,当然你也可以通过 Postman 这种工具来验证。 - -我们试一下所有参数输入正确的情况。 - -```java -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class PersonControllerTest { - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @Test - public void should_get_person_correctly() throws Exception { - Person person = new Person(); - person.setName("SnailClimb"); - person.setSex("Man"); - person.setClassId("82938390"); - person.setEmail("Snailclimb@qq.com"); - - mockMvc.perform(post("/api/person") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(person))) - .andExpect(MockMvcResultMatchers.jsonPath("name").value("SnailClimb")) - .andExpect(MockMvcResultMatchers.jsonPath("classId").value("82938390")) - .andExpect(MockMvcResultMatchers.jsonPath("sex").value("Man")) - .andExpect(MockMvcResultMatchers.jsonPath("email").value("Snailclimb@qq.com")); - } -} -``` - -验证出现参数不合法的情况抛出异常并且可以正确被捕获。 - -```java - @Test - public void should_check_person_value() throws Exception { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - - mockMvc.perform(post("/api/person") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(person))) - .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围")) - .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空")) - .andExpect(MockMvcResultMatchers.jsonPath("email").value("email 格式不正确")); - } -``` - -使用 Postman 验证结果如下: - -![Postman 验证结果](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/postman-validation.png) - -### 验证请求参数(Path Variables 和 Request Parameters) - -**Controller:** - -**一定一定不要忘记在类上加上 `Validated` 注解了,这个参数可以告诉 Spring 去校验方法参数。** - -```java -@RestController -@RequestMapping("/api") -@Validated -public class PersonController { - - @GetMapping("/person/{id}") - public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) { - return ResponseEntity.ok().body(id); - } - - @PutMapping("/person") - public ResponseEntity getPersonByName(@Valid @RequestParam("name") @Size(max = 6,message = "超过 name 的范围了") String name) { - return ResponseEntity.ok().body(name); - } -} - -``` - -**ExceptionHandler:** - -```java - @ExceptionHandler(ConstraintViolationException.class) - ResponseEntity handleConstraintViolationException(ConstraintViolationException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); - } -``` - -**通过测试验证:** - -```java - @Test - public void should_check_param_value() throws Exception { - - mockMvc.perform(get("/api/person/6") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()) - .andExpect(content().string("getPersonByID.id: 超过 id 的范围了")); - } - - @Test - public void should_check_param_value2() throws Exception { - - mockMvc.perform(put("/api/person") - .param("name","snailclimbsnailclimb") - .contentType(MediaType.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()) - .andExpect(content().string("getPersonByName.name: 超过 name 的范围了")); - } -``` - -## 验证 Service 中的方法 - -我们还可以验证任何Spring组件的输入,而不是验证控制器级别的输入,我们可以使用`@Validated`和`@Valid`注释的组合来实现这一需求。 - -**一定一定不要忘记在类上加上 `Validated` 注解了,这个参数可以告诉 Spring 去校验方法参数。** - -```java -@Service -@Validated -public class PersonService { - - public void validatePerson(@Valid Person person){ - // do something - } -} -``` - -**通过测试验证:** - -```java -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class PersonServiceTest { - @Autowired - private PersonService service; - - @Test(expected = ConstraintViolationException.class) - public void should_throw_exception_when_person_is_not_valid() { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - service.validatePerson(person); - } - -} -``` - -## Validator 编程方式手动进行参数验证 - -某些场景下可能会需要我们手动校验并获得校验结果。 - -```java - @Test - public void check_person_manually() { - - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - Validator validator = factory.getValidator(); - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - Set> violations = validator.validate(person); - //output: - //email 格式不正确 - //name 不能为空 - //sex 值不在可选范围 - for (ConstraintViolation constraintViolation : violations) { - System.out.println(constraintViolation.getMessage()); - } - } -``` - -上面我们是通过 `Validator` 工厂类获得的 `Validator` 示例,当然你也可以通过 `@Autowired` 直接注入的方式。但是在非 Spring Component 类中使用这种方式的话,只能通过工厂类来获得 `Validator`。 - -```java -@Autowired -Validator validate -``` - -## 自定以 Validator(实用) - -如果自带的校验注解无法满足你的需求的话,你还可以自定义实现注解。 - -### 案例一:校验特定字段的值是否在可选范围 - -比如我们现在多了这样一个需求:Person类多了一个 region 字段,region 字段只能是`China`、`China-Taiwan`、`China-HongKong`这三个中的一个。 - -第一步你需要创建一个注解: - -```java -@Target({FIELD}) -@Retention(RUNTIME) -@Constraint(validatedBy = RegionValidator.class) -@Documented -public @interface Region { - - String message() default "Region 值不在可选范围内"; - - Class[] groups() default {}; - - Class[] payload() default {}; -} -``` - -第二步你需要实现 `ConstraintValidator`接口,并重写`isValid` 方法: - -```java -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; -import java.util.HashSet; - -public class RegionValidator implements ConstraintValidator { - - @Override - public boolean isValid(String value, ConstraintValidatorContext context) { - HashSet regions = new HashSet<>(); - regions.add("China"); - regions.add("China-Taiwan"); - regions.add("China-HongKong"); - return regions.contains(value); - } -} - -``` - -现在你就可以使用这个注解: - -```java - @Region - private String region; -``` - -### 案例二:校验电话号码 - -校验我们的电话号码是否合法,这个可以通过正则表达式来做,相关的正则表达式都可以在网上搜到,你甚至可以搜索到针对特定运营商电话号码段的正则表达式。 - -`PhoneNumber.java` - -```java -import javax.validation.Constraint; -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -@Documented -@Constraint(validatedBy = PhoneNumberValidator.class) -@Target({FIELD, PARAMETER}) -@Retention(RUNTIME) -public @interface PhoneNumber { - String message() default "Invalid phone number"; - Class[] groups() default {}; - Class[] payload() default {}; -} -``` - -`PhoneNumberValidator.java` - -```java -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -public class PhoneNumberValidator implements ConstraintValidator { - - @Override - public boolean isValid(String phoneField, ConstraintValidatorContext context) { - if (phoneField == null) { - // can be null - return true; - } - return phoneField.matches("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$") && phoneField.length() > 8 && phoneField.length() < 14; - } -} -``` - -搞定,我们现在就可以使用这个注解了。 - -```java -@PhoneNumber(message = "phoneNumber 格式不正确") -@NotNull(message = "phoneNumber 不能为空") -private String phoneNumber; -``` - -## 使用验证组 - -某些场景下我们需要使用到验证组,这样说可能不太清楚,说简单点就是对对象操作的不同方法有不同的验证规则,示例如下(这个就我目前经历的项目来说使用的比较少,因为本身这个在代码层面理解起来是比较麻烦的,然后写起来也比较麻烦)。 - -先创建两个接口: - -```java -public interface AddPersonGroup { -} -public interface DeletePersonGroup { -} -``` -我们可以这样去使用验证组 - -```java -@NotNull(groups = DeletePersonGroup.class) -@Null(groups = AddPersonGroup.class) -private String group; -``` - -```java -@Service -@Validated -public class PersonService { - - public void validatePerson(@Valid Person person) { - // do something - } - - @Validated(AddPersonGroup.class) - public void validatePersonGroupForAdd(@Valid Person person) { - // do something - } - - @Validated(DeletePersonGroup.class) - public void validatePersonGroupForDelete(@Valid Person person) { - // do something - } - -} -``` - -通过测试验证: - -```java - @Test(expected = ConstraintViolationException.class) - public void should_check_person_with_groups() { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - person.setGroup("group1"); - service.validatePersonGroupForAdd(person); - } - - @Test(expected = ConstraintViolationException.class) - public void should_check_person_with_groups2() { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - service.validatePersonGroupForDelete(person); - } -``` - -使用验证组这种方式的时候一定要小心,这是一种反模式,还会造成代码逻辑性变差。 - -代码地址:https://github.com/Snailclimb/springboot-guide/tree/master/source-code/advanced/bean-validation-demo - -## `@NotNull` vs `@Column(nullable = false)`(重要) - -在使用 JPA 操作数据的时候会经常碰到 `@Column(nullable = false)` 这种类型的约束,那么它和 `@NotNull` 有何区别呢?搞清楚这个还是很重要的! - -- `@NotNull`是 JSR 303 Bean验证批注,它与数据库约束本身无关。 -- `@Column(nullable = false)` : 是JPA声明列为非空的方法。 - -总结来说就是即前者用于验证,而后者则用于指示数据库创建表的时候对表的约束。 - -## TODO - -- [ ] 原理分析 - -## 参考 - -- https://reflectoring.io/bean-validation-with-spring-boot/ -- https://www.cnkirito.moe/spring-validation// - diff --git a/docs/basis/spring-boot-devtools.md b/docs/basis/spring-boot-devtools.md deleted file mode 100644 index 16c910e..0000000 --- a/docs/basis/spring-boot-devtools.md +++ /dev/null @@ -1,63 +0,0 @@ -后端开发中热部署有很多方式,但是在开发 SpringBoot 项目有一种 Spring Boot 给我们提供好的很方便的一种方式,配置起来也很简单。 - -> 热部署可以简单的这样理解:我们修改程序代码后不需要重新启动程序,就可以获取到最新的代码,更新程序对外的行为。 - -热部署在我们日常开发可以为我们节省很多时间,通常我们在开发后端的过程中,当我们修改了后端代码之后都需要重启一下项目,这为我们浪费了时间,特别是在项目比较庞大,需要耗费大量时间的启动的时候。**这种方式好像消耗性能挺大的,也需要慎重使用。** - -下面介绍一下如何通过 SpringBoot 提供的 spring-boot-devtools 实现简单的热部署。 - -**依赖:** - -Maven: - -```xml - - org.springframework.boot - spring-boot-devtools - runtime - true - -``` - -```xml - - org.springframework.boot - spring-boot-maven-plugin - -``` - -Gradle: - -```groovy - -configurations { - developmentOnly - runtimeClasspath { - extendsFrom developmentOnly - } -} -dependencies { - developmentOnly("org.springframework.boot:spring-boot-devtools") -} - -``` - - - -**添加配置:** - -ctrl+,(Win) / cmd+(Mac)打开项目配置: - -输入 Compiler , 并且勾选上 Build project automatically - -![dev-tools-idea1](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/dev-tools-idea1.png) - -输入快捷键 ctrl + shift + alt + / (Win)cmd+option+shift+/(Mac),并且选择 Registry - -![dev-tools-idea2](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/dev-tools-idea2.png) - -然后勾选上 Compiler autoMake allow when app running - -![dev-tools-idea3](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/dev-tools-idea3.png) - -很简单,这样你每次修改程序之后就不用重新启动了。 \ No newline at end of file diff --git a/docs/basis/springboot-mybatis.md b/docs/basis/springboot-mybatis.md index 47e6bd4..1955c8c 100644 --- a/docs/basis/springboot-mybatis.md +++ b/docs/basis/springboot-mybatis.md @@ -35,8 +35,6 @@ SpringBoot 整合 Mybatis 有两种常用的方式,一种就是我们常见的 - 数据库:MySQL - SpringBoot版本:2.1.0 - - ### 1.2 创建工程 创建一个基本的 SpringBoot 项目,我这里就不多说这方面问题了,具体可以参考前面的文章。 diff --git a/docs/basis/swagger.md b/docs/basis/swagger.md new file mode 100644 index 0000000..3b83260 --- /dev/null +++ b/docs/basis/swagger.md @@ -0,0 +1,216 @@ +> 若图片无法显示,👉:[Swagger 官方 Starter 配上这个增强方案是真的香!](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247496557&idx=1&sn=77100461596999128e5d721e07f7fe3d&chksm=cea1bca6f9d635b01f45a68a6034faf76c2f5a54223b23b2dc5a0bdb15c7b7bfea0a20a76c1a&token=1835542145&lang=zh_CN#rd) + +这篇文章,我就简单给大家聊聊项目必备的 Swagger 该怎么玩。 + +**何为 Swagger ?** 简单来说,Swagger 就是一套基于 OpenAPI 规范构建的开源工具,可以帮助我们设计、构建、记录以及使用 Rest API。 + +**为何要用 Swagger ?** 前后端分离的情况下,一份 Rest API 文档将会极大的提高我们的工作效率。前端小伙伴只需要对照着 Rest API 文档就可以搞清楚一个接口需要的参数以及返回值。通过 Swagger 我们只需要少量注解即可生成一份自带 UI 界面的 Rest API 文档,不需要我们后端手动编写。并且,通过 UI 界面,我们还可以直接对相应的 API 进行调试,省去了准备复杂的调用参数的过程。 + +这篇文章的主要内容: + +1. SpringBoot 项目中如何使用? +2. Spring Security 项目中如何使用? +3. 使用 knife4j 增强 Swagger + +以下演示所用代码,你可以在这个仓库找到:[https://github.com/Snailclimb/spring-security-jwt-guide](https://github.com/Snailclimb/spring-security-jwt-guide) (从零入门 !Spring Security With JWT(含权限验证)后端部分代码) + +## SpringBoot 项目中如何使用? + +Swagger3.0 官方已经有了自己的 Spring Boot Starter,只需要添加一个 jar 包即可(SpringBoot 版本 2.3.6.RELEASE)。。 + +```xml + + + io.springfox + springfox-boot-starter + 3.0.0 + +``` + +什么都不用配置!直接在浏览器中访问 :[http://ip:port/swagger-ui/](http://ip:port/swagger-ui/) 即可。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-08-1/swagger%E5%9C%A8SpringBoot%E4%B8%AD%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8.png) + +## Spring Security 项目中如何使用? + +如果你的项目使用了 Spring Security 做权限认证的话,你需要为 Swagger 相关 url 添加白名单。 + +```java + String[] SWAGGER_WHITELIST = { + "/swagger-ui.html", + "/swagger-ui/*", + "/swagger-resources/**", + "/v2/api-docs", + "/v3/api-docs", + "/webjars/**" + }; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors().and() + // 禁用 CSRF + .csrf().disable() + .authorizeRequests() + // swagger + .antMatchers(SWAGGER_WHITELIST).permitAll() + ...... + } +``` + +另外,某些请求需要认证之后才可以访问,为此,我们需要对 Swagger 做一些简单的配置。 + +配置的方式非常简单,我提供两种不同的方式给小伙伴们。 + +1. 登录后自动为请求添加 token。 +2. 为请求的 Header 添加一个认证参数,每次请求的时候,我们需要手动输入 token。 + +### 登录后自动为请求添加 token + +通过这种方式我们只需要授权一次即可使用所有需要授权的接口。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-15-1/%E7%99%BB%E5%BD%95%E5%90%8E%E8%87%AA%E5%8A%A8%E4%B8%BA%E8%AF%B7%E6%B1%82%E6%B7%BB%E5%8A%A0token.png) + +```java +/** + * @author shuang.kou + * @description swagger 相关配置 + */ +@Configuration +public class SwaggerConfig { + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("github.javaguide.springsecurityjwtguide")) + .paths(PathSelectors.any()) + .build() + .securityContexts(securityContext()) + .securitySchemes(securitySchemes()); + } + + private List securitySchemes() { + return Collections.singletonList(new ApiKey("JWT", SecurityConstants.TOKEN_HEADER, "header")); + } + + private List securityContext() { + SecurityContext securityContext = SecurityContext.builder() + .securityReferences(defaultAuth()) + .build(); + return Collections.singletonList(securityContext); + } + + List defaultAuth() { + AuthorizationScope authorizationScope + = new AuthorizationScope("global", "accessEverything"); + AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; + authorizationScopes[0] = authorizationScope; + return Collections.singletonList(new SecurityReference("JWT", authorizationScopes)); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Security JWT Guide") + .build(); + } +} +``` + +**未登录前:** + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-15-1/%E8%87%AA%E5%8A%A8%E6%B7%BB%E5%8A%A0token-%E7%99%BB%E5%BD%95%E5%89%8D.png) + +**登录后:** + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-15-1/%E8%87%AA%E5%8A%A8%E6%B7%BB%E5%8A%A0token-%E7%99%BB%E5%BD%95%E5%90%8E.png) + +### 为请求的 Header 添加一个认证参数 + +每次请求的时候,我们需要手动输入 token 到指定位置。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-15-1/%E4%B8%BA%E8%AF%B7%E6%B1%82%E7%9A%84Header%E6%B7%BB%E5%8A%A0%E4%B8%80%E4%B8%AA%E8%AE%A4%E8%AF%81%E5%8F%82%E6%95%B0.png) + +```java +@Configuration +public class SwaggerConfig { + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("github.javaguide.springsecurityjwtguide")) + .paths(PathSelectors.any()) + .build() + .globalRequestParameters(authorizationParameter()) + .securitySchemes(securitySchemes()); + } + + private List securitySchemes() { + return Collections.singletonList(new ApiKey("JWT", SecurityConstants.TOKEN_HEADER, "header")); + } + + private List authorizationParameter() { + RequestParameterBuilder tokenBuilder = new RequestParameterBuilder(); + tokenBuilder + .name("Authorization") + .description("JWT") + .required(false) + .in("header") + .accepts(Collections.singleton(MediaType.APPLICATION_JSON)) + .build(); + return Collections.singletonList(tokenBuilder.build()); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Security JWT Guide") + .build(); + } +} +``` + +## 使用 knife4j 增强 Swagger + +根据官网介绍,knife4j 是为 Java MVC 框架集成 Swagger 生成 Api 文档的增强解决方案。 + +项目地址:[https://gitee.com/xiaoym/knife4j](https://gitee.com/xiaoym/knife4j) 。 + +使用方式非常简单,添加到相关依赖即可(SpringBoot 版本 2.3.6.RELEASE)。 + +```xml + + com.github.xiaoymin + knife4j-spring-boot-starter + 3.0.2 + +``` + +完成之后,访问:[http://ip:port/doc.html](http://ip:port/doc.html) 即可。 + +效果如下。可以看出,相比于 swagger 原生 ui 确实好看实用了很多。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-08-1/image-20201211214120861.png) + +除了 UI 上的增强之外,knife4j 还提供了一些开箱即用的功能。 + +比如:**搜索 API 接口** (`knife4j` 版本>2.0.1 ) + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-08-1/image-20201211214620338.png) + +再比如:**导出离线文档** + +通过 `Knife4j` 我们可以非常方便地导出 Swagger 文档 ,并且支持多种格式。 + +> - markdown:导出当前逻辑分组下所有接口的 Markdown 格式的文档 +> - Html:导出当前逻辑分组下所有接口的 Html 格式的文档 +> - Word:导出当前逻辑分组下所有接口的 Word 格式的文档(自 2.0.5 版本开始) +> - OpenAPI:导出当前逻辑分组下的原始 OpenAPI 的规范 json 结构(自 2.0.6 版本开始) +> - PDF:未实现 + +以 HTML 格式导出的效果图如下。 + +![](https://cdn.jsdelivr.net/gh/javaguide-tech/blog-images-6@main/12-08-1/image-20201211215552314.png) + +还等什么?快去试试吧! \ No newline at end of file diff --git a/docs/interview/springboot-questions.md b/docs/interview/springboot-questions.md deleted file mode 100644 index 501cb05..0000000 --- a/docs/interview/springboot-questions.md +++ /dev/null @@ -1,197 +0,0 @@ -> 本文由JavaGuide整理翻译自(做了适当删减、修改和补充): -> -> - https://www.javaguides.net/2018/11/spring-boot-interview-questions-and-answers.html -> - https://www.algrim.co/posts/101-spring-boot-interview-questions - -### 1. 什么是 Spring Boot? - -首先,重要的是要理解 Spring Boot 并不是一个框架,它是一种创建独立应用程序的更简单方法,只需要很少或没有配置(相比于 Spring 来说)。Spring Boot最好的特性之一是它利用现有的 Spring 项目和第三方项目来开发适合生产的应用程序。 - -### 2. 说出使用Spring Boot的主要优点 - -1. 开发基于 Spring 的应用程序很容易。 -2. Spring Boot 项目所需的开发或工程时间明显减少,通常会提高整体生产力。 -3. Spring Boot不需要编写大量样板代码、XML配置和注释。 -4. Spring引导应用程序可以很容易地与Spring生态系统集成,如Spring JDBC、Spring ORM、Spring Data、Spring Security等。 -5. Spring Boot遵循“固执己见的默认配置”,以减少开发工作(默认配置可以修改)。 -6. Spring Boot 应用程序提供嵌入式HTTP服务器,如Tomcat和Jetty,可以轻松地开发和测试web应用程序。(这点很赞!普通运行Java程序的方式就能运行基于Spring Boot web 项目,省事很多) -7. Spring Boot提供命令行接口(CLI)工具,用于开发和测试Spring Boot应用程序,如Java或Groovy。 -8. Spring Boot提供了多种插件,可以使用内置工具(如Maven和Gradle)开发和测试Spring Boot应用程序。 - -### 3. 为什么需要Spring Boot? - -Spring Framework旨在简化J2EE企业应用程序开发。Spring Boot Framework旨在简化Spring开发。 - -![why-we-need-springboot](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/why-we-need-springboot.png) - -### 4. 什么是 Spring Boot Starters? - -Spring Boot Starters 是一系列依赖关系的集合,因为它的存在,项目的依赖之间的关系对我们来说变的更加简单了。举个例子:在没有Spring Boot Starters之前,我们开发REST服务或Web应用程序时; 我们需要使用像Spring MVC,Tomcat和Jackson这样的库,这些依赖我们需要手动一个一个添加。但是,有了 Spring Boot Starters 我们只需要一个只需添加一个**spring-boot-starter-web**一个依赖就可以了,这个依赖包含的字依赖中包含了我们开发REST 服务需要的所有依赖。 - -```xml - - org.springframework.boot - spring-boot-starter-web - -``` - -### 5. 如何在Spring Boot应用程序中使用Jetty而不是Tomcat? - -Spring Boot Web starter使用Tomcat作为默认的嵌入式servlet容器, 如果你想使用 Jetty 的话只需要修改pom.xml(Maven)或者build.gradle(Gradle)就可以了。 - -**Maven:** - -```xml - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.springframework.boot - spring-boot-starter-jetty - -``` - -**Gradle:** - -```groovy -compile("org.springframework.boot:spring-boot-starter-web") { - exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' -} -compile("org.springframework.boot:spring-boot-starter-jetty") -``` - -说个题外话,从上面可以看出使用 Gradle 更加简洁明了,但是国内目前还是 Maven 使用的多一点,我个人觉得 Gradle 在很多方面都要好很多。 - -### 6. 介绍一下@SpringBootApplication注解 - -```java -package org.springframework.boot.autoconfigure; -@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 { - ...... -} -``` - -```java -package org.springframework.boot; -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Configuration -public @interface SpringBootConfiguration { - -} -``` - -可以看出大概可以把 `@SpringBootApplication `看作是 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan ` 注解的集合。根据 SpringBoot官网,这三个注解的作用分别是: - -- `@EnableAutoConfiguration`:启用 SpringBoot 的自动配置机制 -- `@ComponentScan`: 扫描被`@Component` (`@Service`,`@Controller`)注解的bean,注解默认会扫描该类所在的包下所有的类。 -- `@Configuration`:允许在上下文中注册额外的bean或导入其他配置类 - -### 7. (重要)Spring Boot 的自动配置是如何实现的? - -这个是因为`@SpringBootApplication `注解的原因,在上一个问题中已经提到了这个注解。我们知道 `@SpringBootApplication `看作是 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan ` 注解的集合。 - -- `@EnableAutoConfiguration`:启用 SpringBoot 的自动配置机制 -- `@ComponentScan`: 扫描被`@Component` (`@Service`,`@Controller`)注解的bean,注解默认会扫描该类所在的包下所有的类。 -- `@Configuration`:允许在上下文中注册额外的bean或导入其他配置类 - -`@EnableAutoConfiguration`是启动自动配置的关键,源码如下(建议自己打断点调试,走一遍基本的流程): - -```java -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import org.springframework.context.annotation.Import; - -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -@AutoConfigurationPackage -@Import({AutoConfigurationImportSelector.class}) -public @interface EnableAutoConfiguration { - String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; - - Class[] exclude() default {}; - - String[] excludeName() default {}; -} -``` - -`@EnableAutoConfiguration` 注解通过Spring 提供的 `@Import` 注解导入了`AutoConfigurationImportSelector`类(`@Import` 注解可以导入配置类或者Bean到当前类中)。 - -` ``AutoConfigurationImportSelector`类中`getCandidateConfigurations`方法会将所有自动配置类的信息以 List 的形式返回。这些配置信息会被 Spring 容器作 bean 来管理。 - -```java - protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { - List configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), - getBeanClassLoader()); - Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " - + "are using a custom packaging, make sure that file is correct."); - return configurations; - } -``` - -自动配置信息有了,那么自动配置还差什么呢? - -`@Conditional` 注解。`@ConditionalOnClass`(指定的类必须存在于类路径下),`@ConditionalOnBean`(容器中是否有指定的Bean)等等都是对`@Conditional`注解的扩展。拿 Spring Security 的自动配置举个例子: - -`SecurityAutoConfiguration`中导入了`WebSecurityEnablerConfiguration`类,`WebSecurityEnablerConfiguration`源代码如下: - -```java -@Configuration -@ConditionalOnBean(WebSecurityConfigurerAdapter.class) -@ConditionalOnMissingBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN) -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -@EnableWebSecurity -public class WebSecurityEnablerConfiguration { - -} -``` - -`WebSecurityEnablerConfiguration`类中使用`@ConditionalOnBean`指定了容器中必须还有`WebSecurityConfigurerAdapter` 类或其实现类。所以,一般情况下 Spring Security 配置类都会去实现 `WebSecurityConfigurerAdapter`,这样自动将配置就完成了。 - -更多内容可以参考这篇文章:https://sylvanassun.github.io/2018/01/08/2018-01-08-spring_boot_auto_configure/ - -### 8. Spring Boot支持哪些嵌入式web容器? - -Spring Boot支持以下嵌入式servlet容器: - -| **Name** | **Servlet Version** | -| ------------ | ------------------- | -| Tomcat 9.0 | 4.0 | -| Jetty 9.4 | 3.1 | -| Undertow 2.0 | 4.0 | - -您还可以将Spring引导应用程序部署到任何Servlet 3.1+兼容的 Web 容器中。 - -这就是你为什么可以通过直接像运行 普通 Java 项目一样运行 SpringBoot 项目。这样的确省事了很多,方便了我们进行开发,降低了学习难度。 - -### 9. 什么是Spring Security ? - -Spring Security 应该属于 Spring 全家桶中学习曲线比较陡峭的几个模块之一,下面我将从起源和定义这两个方面来简单介绍一下它。 - -- **起源:** Spring Security 实际上起源于 Acegi Security,这个框架能为基于 Spring 的企业应用提供强大而灵活安全访问控制解决方案,并且框架这个充分利用 Spring 的 IoC 和 AOP 功能,提供声明式安全访问控制的功能。后面,随着这个项目发展, Acegi Security 成为了Spring官方子项目,后来被命名为 “Spring Security”。 -- **定义:**Spring Security 是一个功能强大且高度可以定制的框架,侧重于为Java 应用程序提供身份验证和授权。——[官方介绍](https://spring.io/projects/spring-security)。 \ No newline at end of file diff --git "a/docs/projects/SpringCloud\345\210\267\351\242\230\347\263\273\347\273\237.md" "b/docs/projects/SpringCloud\345\210\267\351\242\230\347\263\273\347\273\237.md" new file mode 100644 index 0000000..2309eab --- /dev/null +++ "b/docs/projects/SpringCloud\345\210\267\351\242\230\347\263\273\347\273\237.md" @@ -0,0 +1,121 @@ +> 推荐👍: +> - [接近100K star 的 Java 学习/面试指南](https://github.com/Snailclimb/JavaGuide) +> - [Github 95k+点赞的 Java 面试/学习手册.PDF](https://www.yuque.com/docs/share/f0c5ffbc-48b5-45f3-af66-2a5e6f212595) + +今天给小伙伴们推荐一个朋友开源的面试刷题系统。 + +这篇文章我会从系统架构设计层面详解介绍这个开源项目,并且会把微服务常用的一些技术都介绍一下。即使你对这个项目不感兴趣,也能了解到很多微服务相关的知识。美滋滋! + +_昨晚肝了很久~原创不易,若有帮助,求赞求转发啊!_ + +不得不说,这个刷题系统确实是有点东西,你真的值得拥有!首先,这是一个微服务的项目,其次这个系统涵盖了市面上常用的主流技术比如 SpringBoot、Spring Cloud 等等(后面会详细介绍)。 + +不论是你想要学习分布式的技术,还是想找一个实战项目练手或者作为自己的项目经验,这个项目都非常适合你。 + +另外,因为项目作者提供了详细的技术文档,所以你不用担心上手太难! + +![PassJava文档](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-12-21/PassJava%E6%96%87%E6%A1%A3%E5%9C%B0%E5%9D%80.png) + +## 效果图 + +我们先来看看这个面试刷题系统的效果图。这里我们只展示的是这个系统的前端(微信小程序),后台管理系统这里就不展示了。 + +![PassJava前端展示](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-12-21/PassJava%E5%89%8D%E7%AB%AF%E5%B1%95%E7%A4%BA.png) + +可以看到,除了少部分地方的颜色搭配比较难看之外,页面整体 UI 还是比较美观的。 + +## 技术栈 + +再聊聊大家最关心的问题:“**这套系统的技术栈是什么样的呢?**”。 + +这套系统采用了目前企业都在用的主流技术:SpringBoot(基础框架)、Spring Cloud(微服务)、MyBatis(ORM框架)、Redis(缓存)、MySql(关系型数据库)、MongoDB(NoSQL)、RabbitMQ(消息队列)、Elasticsearch(搜索引擎)。并且,这个系统是以 Docker 容器化的方式进行部署的。非常实用! + +## 系统架构设计 + +了解了技术栈之后,那必然需要简单了解一下整个 **系统的架构设计** ,这是系统的灵魂所在了(图源:[PassJava 官方文档](http://jayh2018.gitee.io/passjava-learning/#/01.项目简介/2.项目微服务架构图 "PassJava官方文档"))。 + +![](http://cdn.jayh.club/blog/20200407/scg1XhlvGbUV.png?imageslim) + +### 网关 + +网关负责认证授权、限流、熔断、降级、请求分发、负载均衡等等操作。一般情况下,网关一般都会提供这些功能。 + +这里使用的是 **Spring Cloud Gateway** 作为网关。Spring Cloud Gateway 是 Spring Cloud 官方推出的第二代网关框架,目的是取代 netflix 的 Zuul 网关。 + +### 注册中心和配置中心 + +注册中心和配置中心这块使用的是阿里巴巴开源的 **Nacos** 。Nacos 目前属于 Spring Cloud Alibaba 中的一员。主要用于发现、配置和管理微服务,类似于 Consul、Eureka。并且,提供了分布式配置管理功能。 + +Nacos 的基本介绍如下(图源:[官网文档-什么是 Nacos](https://nacos.io/zh-cn/docs/what-is-nacos.html "官网文档-什么是 Nacos")): + +![nacos_map](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-12-21/nacosMap.jpg) + +详解介绍一下 Nacos 在这个项目中提供的两个核心功能: + +- **注册中心** :API 网关通过注册中心实时获取到服务的路由地址,准确地将请求路由到各个服务。 +- **配置中心** :传统的配置方式需要重新启动服务。如果服务很多,则需要重启所有服务,非常不方便。通过 Nacos,我们可以动态配置服务。并且,Nacos 提供了一个简洁易用的 UI 帮助我们管理所有的服务和应用的配置。 + +关于配置中心,我们这里再拓展一下,除了 Nacos ,还有 Apollo、SpringCloud Config、K8s ConfigMap 可供选择。 + +### 分布式链路追踪 + +> 不同于单体架构,在分布式架构下,请求需要在多个服务之间调用,排查问题会非常麻烦。我们需要分布式链路追踪系统来解决这个痛点。 + +分布式链路追踪这块使用的是 Twitter 的 **Zipkin** ,并且结合了 **Spring Cloud Sleuth** 。 + +Spring Cloud Sleuth 只是做一些链路追踪相关的数据记录,我们可以使用 Zipkin Server 来处理这些数据。 + +相关阅读:[《40 张图看懂分布式追踪系统原理及实践》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247492112&idx=3&sn=4eb100f4ecef98a475d7f7650c993222&chksm=cea1addbf9d624cdc0e868d3b72edf40a7a6880218ecb1a9ddbac50423d20dceceb8dca804f4&token=2007747701&lang=zh_CN#rd) 。 + +### 监控系统 + +监控系统可以帮助我们监控应用程序的状态,并且能够在风险发生前告警。 + +监控系统这块使用的是 **Prometheus + Grafana**。Prometheus 负责收集监控数据,Grafana 用于展示监控数据。我们直接将 Grafana 的数据源选择为 Prometheus 即可。 + +关于监控系统更详细的技术选型,可以看这篇文章:[《监控系统选型看这一篇够了!选择 Prometheus 还是 Zabbix ?》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247490068&idx=2&sn=3ac42f6891fec8906230cc9e0ec28ba7&chksm=cea255dff9d5dcc9369c9c30eb55925cd16045d914cbfe194ea7d5630c3339630d731d654527&token=2007747701&lang=zh_CN#rd) 。 + +### 消息队列 + +我们知道,消息队列主要能为系统带来三点好处: + +1. **通过异步处理提高系统性能(减少响应所需时间)。** +2. **削峰/限流** +3. **降低系统耦合性。** + +常用的消息队列有:RabbitMQ(本系统所采用的方案)、Kafka、RocketMQ。 + +### 缓存 + +缓存这里使用的是 Redis ,老生常谈了,这里就不再多做介绍。 + +另外, 为了保证缓存服务的高可用,我们使用 Redis 官方提供了一种 Redis 集群的解决方案 Redis Sentinel 来管理 Redis 集群。 + +### 数据库 + +数据库这里使用的是 MySQL ,并使用主从模式实现读写分离,以提高读性能。 + +### 对象存储 + +由于是分布式系统,传统的将文件上传到本机已经没办法满足我们的需求了。 + +由于自己搭建分布式文件系统也比较麻烦,所以对象存储这里我们使用的是阿里云 OSS,它主要用于存储一些文件比如图片。 + +### 快速开发脚手架 + +另外,为了后台的快速搭建这里使用的是 **[renren-fast](https://gitee.com/renrenio/renren-fast "renren-fast")** 快速开发脚手架。使用这个脚手架配合上代码生成器 **[renren-generator](https://gitee.com/renrenio/renren-generator "renren-generator")** ,我们可以快速生成 70%左右的前后端代码。绝对是快速开发项目并交付以及接私活的利器了! + +我在之前的也推荐过这个脚手架,详情请看下面这两篇文章: + +1. [听说你要接私活?Guide 连夜整理了 5 个开源免费的 Java 项目快速开发脚手架。](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247487002&idx=1&sn=e9db79f1bbd561b3ead1c9475f8fd7f5&chksm=cea241d1f9d5c8c72fa33764208a26a26de5d2d3e4ac2a6794e0792ba779bb11414b3fd506e3&token=2007747701&lang=zh_CN#rd) +2. [解放双手,再来推荐 5 个 Java 项目开发快速开发脚手架!项目经验和私活都不愁了!](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247487467&idx=1&sn=c2d2bd28918b58d8646f1441791aeaaf&chksm=cea24020f9d5c9364afc22013fac3266fabffcaa370f708434a6a304274c6b1d8bce235b7a24&token=2007747701&lang=zh_CN#rd) + +## 总结 + +这篇文章我主要从架构设计层面分析了朋友开源的这个基于微服务的刷题系统。 + +当然了,朋友使用微服务开发这个项目的主要目的也是为了自己实践微服务相关的知识,同时也是为了给需要微服务相关实战项目经验的小伙伴一个可以学习的项目。不然的话,直接用单体就完事了,完全可以支撑这个项目目前的并发量以及可预见的未来的并发量。 + +- 项目地址:https://github.com/Jackson0714/PassJava-Platform +- 文档地址:http://jayh2018.gitee.io/passjava-learning/#/ + diff --git "a/docs/projects/kkFileView-SpringBoot\345\234\250\347\272\277\346\226\207\344\273\266\351\242\204\350\247\210\347\263\273\347\273\237.md" "b/docs/projects/kkFileView-SpringBoot\345\234\250\347\272\277\346\226\207\344\273\266\351\242\204\350\247\210\347\263\273\347\273\237.md" new file mode 100644 index 0000000..19d09a0 --- /dev/null +++ "b/docs/projects/kkFileView-SpringBoot\345\234\250\347\272\277\346\226\207\344\273\266\351\242\204\350\247\210\347\263\273\347\273\237.md" @@ -0,0 +1,239 @@ +> 昨晚搭建环境都花了好一会时间,主要在浪费在了安装 openoffice 这个依赖环境上(_Mac 需要手动安装_)。 +> +> 然后,又一步一步功能演示,记录,调试项目,并且简单研究了一下核心代码之后才把这篇文章写完。 +> +> 另外,这篇文章我还会简单分析一下项目核心代码。 +> +> _如果有帮助,欢迎点赞/再看鼓励,我会开心很久 ღ( ´・ᴗ・` )比心_ + +## 项目介绍 + +官方是这样介绍 kkFileView 的: + +> kkFileView 是使用 spring boot 打造文件文档在线预览项目解决方案,支持 doc、docx、ppt、pptx、xls、xlsx、zip、rar、mp4、mp3 以及众多类文本如 txt、html、xml、java、properties、sql、js、md、json、conf、ini、vue、php、py、bat、gitignore 等文件在线预览 + +**简单来说 kkFileView 就是常见的文件类型的在线预览解决方案。** + +总的来说我觉得 kkFileView 是一个非常棒的开源项目,在线文件预览这个需求非常常见。感谢开源! + +下面, 我站在一个“上帝”的角度从多个维度来评价一下 kkFileView: + +1. 代码质量一般,有很多可以优化的地方比如: + - `Controller` 层代码嵌套太多逻辑 + - 没有进行全局异常处理(_代码中是直接返回错误信息的 json 数据给前端,我并不推荐这样做_) + - 返回值不需要通过`ObjectMapper`转换为 JSON 格式(`ResponseEntity`+`@RestController` 就行了) + - ...... +2. 使用的公司比较多,说明项目整体功能还是比较稳定和成熟的! +3. 代码整体逻辑还是比较清晰的,比较容易看懂,给作者们点个赞! + +## 环境搭建 + +### 克隆项目 + +通过以下命令即可将项目克隆到本地: + +```bash +git clone https://gitee.com/kekingcn/file-online-preview.git +``` + +### 安装 OpenOffice + +office 类型的文件的预览依赖了 OpenOffice ,所以我们首先要安装 OpenOffice(Windows 下已内置,Linux 会自动安装,Mac OS 下需要手动安装)。 + +下面演示一下如何在 Mac 上安装 OpenOffice。 + +你可以通过以下命令安装最新版的 OpenOffice: + +```bash +brew cask install openoffice +``` + +不过,这种方式下载可能会比较慢,你可以直接去官网下载 dmg 安装包。 + +官方下载地址:[https://www.openoffice.org/download/](https://www.openoffice.org/download/) + +![OpenOffice下载 ](https://img-blog.csdnimg.cn/20201015194327797.png) + +很多小伙伴就要问了:**OpenOffice 是什么呢?** + +[OpenOffice](https://www.openoffice.org/) 是 Apache 旗下的一款开源免费的文字处理软件,支持 Windows、Liunx、OS X 等主流操作系统。 + +OpenOffice 和 Windows 下 office 办公软件有点类似,不过其实开源免费的。 + +![why openoffice](https://img-blog.csdnimg.cn/20201015194328447.png) + +### 启动项目 + +运行`FilePreviewApplication`的 main 方法,服务启动后,访问[http://localhost:8012/](http://localhost:8012/) 会看到如下界面,代表服务启动成功。 + +![项目启动成功](https://img-blog.csdnimg.cn/20201015194328801.png) + +## 使用 + +我们首先上传了 3 个不同的类型的文件来分别演示一下图片、PDF、Word 文档的预览。 + +![](https://img-blog.csdnimg.cn/20201015194328978.png) + +### 图片的预览 + +**kkFileView 支持 jpg,jpeg,png,gif 等多种格式图片的预览,还包括了翻转,缩放图片等操作。** + +图片的预览效果如下。 + +![图片的预览效果](https://img-blog.csdnimg.cn/20201015194329517.png) + +### Word 文档的预览 + +**kkFileView 支持 doc,docx 文档预览。** + +另外,根据 Word 大小以及网速问题, Word 预览提供了两种模式: + +- 每页 Word 转为图片预览 +- 整个 Word 文档转成 PDF,再预览 PDF。 + +两种模式的适用场景如下 + +- **图片预览** :Word 文件大(加载 PDF 速度比较慢)的情况。 +- **PDF 预览** :内网访问(加载 PDF 速度比较快)的情况。 + +图片预览模式预览效果如下: + +![](https://img-blog.csdnimg.cn/20201015194329908.png) + +PDF 预览模式预览效果如下: + +![](https://img-blog.csdnimg.cn/20201015194330591.png) + +### PDF 文档的预览 + +kkFileView 支持 PDF 文档预览。类似 Word 文档预览, PDF 预览提供了两种模式: + +- 每页 Word 转为图片预览 +- 整个 Word 文档转成 PDF,再预览 PDF。 + +由于和 Word 文档的预览展示效果一致,这里就不放图片了。 + +## 文件预览核心代码分析 + +### API 层 + +文件预览调用的接口是 `/onlinePreview` 。 + +通过分析 `/onlinePreview` 接口我们发现, 后端接收到预览请求之后,会从 URL 和请求中筛选出自己需要的信息比如文件后缀、文件名。 + +之后会调用`FilePreview`类 的 `filePreviewHandle()` 方法。`filePreviewHandle()` 方法是实现文件预览的核心方法。 + +```java +@RequestMapping(value = "/onlinePreview") +public String onlinePreview(String url, Model model, HttpServletRequest req) { + FileAttribute fileAttribute = fileUtils.getFileAttribute(url); + req.setAttribute("fileKey", req.getParameter("fileKey")); + model.addAttribute("pdfDownloadDisable", ConfigConstants.getPdfDownloadDisable()); + model.addAttribute("officePreviewType", req.getParameter("officePreviewType")); + FilePreview filePreview = previewFactory.get(fileAttribute); + logger.info("预览文件url:{},previewType:{}", url, fileAttribute.getType()); + return filePreview.filePreviewHandle(url, model, fileAttribute); +} +``` + +`FilePreview` 是文件预览接口,不同的文件类型的预览都实现了 `FilePreview` 接口,并实现了 `filePreviewHandle()` 方法。 + +### 文件预览接口 + +```java +public interface FilePreview { + String filePreviewHandle(String url, Model model, FileAttribute fileAttribute); +} +``` + +不同的文件类型的预览都实现了 `FilePreview` 接口,如下图所示。 + +![](https://img-blog.csdnimg.cn/20201015194330836.png) + +不同文件类型的预览都会实现 `FilePreview` 接口,然后重写`filePreviewHandle()`方法。比如: `OfficeFilePreviewImpl` 这个主要负责处理 office 文件的预览、`PdfFilePreviewImpl` 主要负责处理 pdf 文件的预览。 + +### 文件预览具体实现分析 + +下面我们以 office 文件的预览为入口来分析。 + +首先要明确的是 excel 类型的预览是通过将 excel 文件转换为 HTML 实现的,其他类型 office 文件的预览是通过将文件转换为 PDF 或者是 图片的方式来预览的。 + +举个例子。我们上传了一份名为 `武汉市文化市场管理办法.docx` 的 Word 文件并预览的话,`jodconverter-web/src/main/file` 路径下会生成两个相关文件,这两个文件分别对应了我们提到的 PDF 预览 和 图片预览这两种方式。 + +- `武汉市文化市场管理办法.pdf` +- 由 Word 文件所转化得到的一系列图片 + +![](https://img-blog.csdnimg.cn/2020101519433136.png) + +我们以一个名为 `武汉市文化市场管理办法.docx` 的文件来举例说明一下代码中是如何做的。 + +通过分析代码, 我们定位到了 `OfficeFilePreviewImpl` 这个主要负责处理 office 文件预览的类。 + +```java +/** + * 处理office文件 + */ +@Service +public class OfficeFilePreviewImpl implements FilePreview { + +} +``` + +我们来简单分析一下 `OfficeFilePreviewImpl` 类中实现预览的核心方法是 `filePreviewHandle` 。 + +> 说明:这部分代码的逻辑不够清晰,还可以抽方法优化以让人更容易读懂,感兴趣的小伙伴可以自己动手重构一下,然后去给作者提个 PR。 + +```java + @Override + public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) { + // 1.获取预览类型(image/pdf/html),用户请求中传了officePreviewType参数就取参数的,没传取系统默认(image) + String officePreviewType = model.asMap().get("officePreviewType") == null ? ConfigConstants.getOfficePreviewType() : model.asMap().get("officePreviewType").toString(); + // 2.获取 URL 地址 + String baseUrl = BaseUrlFilter.getBaseUrl();// http://localhost:8012/ + // 3.获取图片相关信息 + String suffix=fileAttribute.getSuffix();//文件后缀如docx + String fileName=fileAttribute.getName();//文件名如:武汉市文化市场管理办法.docx + // 4. 判断是否为 html 格式预览也就是判断文件否为 excel + boolean isHtml = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx"); + // 5. 将文件的后缀名更换为 .pdf 或者 .html(excel文件的情况) + String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + (isHtml ? "html" : "pdf"); + // 6. 转换后的文件输出的文件夹如 file-online-preview/jodconverter-web/src/main/file/武汉市文化市场管理办法.pdf) + String outFilePath = FILE_DIR + pdfName; + // 7 .判断之前是否已转换过,如果转换过,直接返回,否则执行转换 + // 文件第一次被预览的时候会首先对文件进行缓存处理 + if (!fileUtils.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) { + String filePath; + // 下载文件 + ReturnResponse response = downloadUtils.downLoad(fileAttribute, null); + if (0 != response.getCode()) { + model.addAttribute("fileType", suffix); + model.addAttribute("msg", response.getMsg()); + return "fileNotSupported"; + } + filePath = response.getContent(); + if (StringUtils.hasText(outFilePath)) { + officeToPdf.openOfficeToPDF(filePath, outFilePath); + if (isHtml) { + // 对转换后的文件进行操作(改变编码方式) + fileUtils.doActionConvertedFile(outFilePath); + } + if (ConfigConstants.isCacheEnabled()) { + // 加入缓存 + fileUtils.addConvertedFile(pdfName, fileUtils.getRelativePath(outFilePath)); + } + } + } + // 8.根据预览类型officePreviewType,选择不同的预览方式 + // 比如,如果预览类型officePreviewType为pdf则进行pdf方式预览 + if (!isHtml && baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) { + return getPreviewType(model, fileAttribute, officePreviewType, baseUrl, pdfName, outFilePath, pdfUtils, OFFICE_PREVIEW_TYPE_IMAGE); + } + model.addAttribute("pdfUrl", pdfName); + return isHtml ? "html" : "pdf"; + } + +``` + +项目地址: [https://github.com/kekingcn/kkFileView](https://github.com/kekingcn/kkFileView) 。 + + diff --git "a/docs/projects/\344\270\200\344\270\252\345\237\272\344\272\216SpringBoot\347\232\204\345\234\250\347\272\277\350\200\203\350\257\225\347\263\273\347\273\237.md" "b/docs/projects/\344\270\200\344\270\252\345\237\272\344\272\216SpringBoot\347\232\204\345\234\250\347\272\277\350\200\203\350\257\225\347\263\273\347\273\237.md" new file mode 100644 index 0000000..0c92bf0 --- /dev/null +++ "b/docs/projects/\344\270\200\344\270\252\345\237\272\344\272\216SpringBoot\347\232\204\345\234\250\347\272\277\350\200\203\350\257\225\347\263\273\347\273\237.md" @@ -0,0 +1,174 @@ +[大家好!我是 Guide 哥,Java 后端开发。一个会一点前端,喜欢烹饪的自由少年。](https://www.yuque.com/docs/share/71251673-1fef-416e-93d7-489a25a9eda5?#%20%E3%80%8A%E8%B5%B0%E8%BF%91JavaGuide%E3%80%8B) + +## 前言 + +最近看到了一个考试系统,感觉做的挺不错,并且也比较成熟,所以我就简单玩了一下。另外,考试系统应用场景还挺多的,不论是对于在校大学生还是已经工作的小伙伴,并且,类似的私活也有很多。 + +![在线考试系统后台管理主页](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/FireShot%20Capture%20027%20-%20%E4%B8%BB%E9%A1%B5%20-%20localhost.png) + +下面我就把这个项目分享给小伙伴们,非常值得学习,拿来即用! + +_为了一步一步演示,让小伙伴们都能成功部署/运行项目, Guide 哥自己本地搭建了项目环境,并将项目成功跑了起来。照着我的步骤,新手也能成功把项目跑起来!_ + +_如果你“感动”的话,点个赞/在看,就是对我最大的支持!_ + +另外,以下内容不涉及代码分析,整体代码结构比较清晰,熟悉了基本功能之后会很容易看明白。 + +## 介绍 + +[uexam](https://gitee.com/mindskip/uexam) 是一款前后端分离的在线考试系统。这款在线考试系统,不光支持 web 端,同时还支持微信小程序端。 + +[uexam](https://gitee.com/mindskip/uexam) 界面设计美观,代码整体结构清晰,表设计比较规范。 + +[uexam](https://gitee.com/mindskip/uexam) 后端基于 Spring Boot 2.0+MySQL/PostgreSQL+Redis+MyBatis,前端基于 Vue,采用前端后端分离开发! + +另外,这个项目提供了 MySQL 和 PostgreSQL 两种不同的数据库版本,下面我以 PostgreSQL 数据库版本的来演示(_建议大家使用和体验 PostgreSQL 版本_)。 + +项目地址:[https://gitee.com/SnailClimb/uexam](https://gitee.com/SnailClimb/uexam) 。 + +## 软件架构 + +![软件架构图](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E8%BD%AF%E4%BB%B6%E6%9E%B6%E6%9E%84%E5%9B%BE.jpg) + +## 使用效果 + +样式以及操作体验都是非常不错的,这也是我推荐这个项目很重要的一个原因。 + +### 管理端 + +#### 添加学科 + +在创建题目之前,你需要首要创建学科。这里我们创建的学科是编程,年级是三年级。 + +![添加学科](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E6%B7%BB%E5%8A%A0%E5%AD%A6%E7%A7%91.jpg) + +#### 添加题目 + +可以看到这里可以添加多种题型: 单选题、多选题、判断题、填空题、简答题。 + +![添加题目](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E6%B7%BB%E5%8A%A0%E9%A2%98%E7%9B%AE.jpg) + +我们以单选题为例,添加题目界面如下。 + +![添加题目页面](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/iShot2020-09-03%E4%B8%8B%E5%8D%8805.25.30.jpg) + +添加成功之后,题目列表就会出现我们刚刚添加的题目。 + +![题目创建成功](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E9%A2%98%E7%9B%AE%E5%88%9B%E5%BB%BA%E6%88%90%E5%8A%9F.jpg) + +#### 添加试卷 + +有了学科和题目之后才能添加试卷。 + +![添加试卷](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E6%B7%BB%E5%8A%A0%E8%AF%95%E5%8D%B7.jpg) + +添加成功之后,试卷列表就会出现我们刚刚添加的试卷。 + +![试卷创建成功](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E8%AF%95%E5%8D%B7%E5%88%9B%E5%BB%BA%E6%88%90%E5%8A%9F.jpg) + +#### 添加学生 + +**注意:这里的学生要和我们前面创建的学科对应的年级对应上。** + +![添加学生](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E6%B7%BB%E5%8A%A0%E5%AD%A6%E7%94%9F.jpg) + +### 学生端 + +使用我们刚刚创建的学生账号登录,你会发现主页多了一个试卷。这个试卷就是我们刚刚在管理端创建的。 + +![学生端-主页](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E5%AD%A6%E7%94%9F%E7%AB%AF-%E4%B8%BB%E9%A1%B5.jpg) + +试卷答题界面如下。 + +![学生端-试卷](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/%E5%AD%A6%E7%94%9F%E7%AB%AF-%E8%AF%95%E5%8D%B7.jpg) + +## 启动 + +### 后端 + +我们这里以 PostgreSQL 数据库版本来演示。 + +#### 安装 PostgreSQL + +**这里我们使用 Docker 下载最近版的 PostgreSQL 镜像 ,默认大家已经安装了 Docker。** + +```bash +$ docker pull postgres +``` + +**查看 PostgreSQL 镜像:** + +```bash +$ docker images |grep postgres +postgres latest 62473370e7ee 2 weeks ago 314MB +``` + +**运行 PostgreSQL:** + +```bash +$ docker run -d -p 5432:5432 --name postgresql -e POSTGRES_PASSWORD=123456 postgres +``` + +#### 安装 Redis + +**这里我们使用 Docker 下载最近版的 Redis 镜像 ,默认大家已经安装了 Docker。** + +```bash +$ docker pull redis +``` + +**查看 Redis 镜像:** + +```bash +$ docker images |grep redis +``` + +**运行 Redis:** + +```bash +$ docker run -itd --name redis-test -p 6379:6379 redis +``` + +#### 创建数据库并执行数据库脚本 + +首先创建一个名字叫做`xzs` 的数据库,然后执行相应的数据库脚本即可(数据库脚本在 `uexam/source/xzs/sql` 目录下。)。 + +#### 配置文件修改 + +使用 IntelliJ IDEA 打开 `uexam/source/xzs` (后台代码),修改 `application-dev.yml` ,将 postgesql/mysql、redis 的服务地址改为自己本地的。 + +#### 启动项目 + +直接运行 `XzsApplication` 即可。 + +![](https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/2020-9/image-20200903180710467.png) + +启动成功后,打开下面的链接即可跳转到对应的端: + +- 学生系统地址:http://localhost:8000/student +- 管理端地址:http://localhost:8000/admin + +**注意:这种方式,前端虽然也启动了,也能访问,不过是内嵌在后端项目中。如果如果我们需要前后端分离的话,需要单独运行前端项目** + +### 前端 + +小程序端的就不演示了,我这里只演示一下 web 端的。 + +web 端代码在 `uexam/source/vue` 下,我们需要首先进入这个目录,然后分别对 `xzs-admin` (管理端) 和 `xzs-student` (学生端)执行下面两个命令。 + +**1.下载相关依赖** + +```bash +$ npm install +``` + +**2.启动项目** + +```bash +$ npm run serve +``` + +启动完成之后,打开下面的链接即可跳转到对应的端: + +- 学生系统地址:http://localhost:8001 +- 管理端地址:http://localhost:8002 \ No newline at end of file diff --git a/docs/spring-bean-validation.md b/docs/spring-bean-validation.md new file mode 100644 index 0000000..5839a28 --- /dev/null +++ b/docs/spring-bean-validation.md @@ -0,0 +1,584 @@ +数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。 + +最普通的做法就像下面这样。我们通过 `if/else` 语句对请求的每一个参数一一校验。 + +```java +@RestController +@RequestMapping("/api/person") +public class PersonController { + + @PostMapping + public ResponseEntity save(@RequestBody PersonRequest personRequest) { + if (personRequest.getClassId() == null + || personRequest.getName() == null + || !Pattern.matches("(^Man$|^Woman$|^UGM$)", personRequest.getSex())) { + + } + return ResponseEntity.ok().body(personRequest); + } +} +``` + +这样的代码,小伙伴们在日常开发中一定不少见,很多开源项目都是这样对请求入参做校验的。 + +但是,不太建议这样来写,这样的代码明显违背了 **单一职责原则**。大量的非业务代码混杂在业务代码中,非常难以维护,还会导致业务层代码冗杂! + +实际上,我们是可以通过一些简单的手段对上面的代码进行改进的!这也是本文主要要介绍的内容! + +废话不多说!下面我会结合自己在项目中的实际使用经验,通过实例程序演示如何在 SpringBoot 程序中优雅地的进行参数验证(普通的 Java 程序同样适用)。 + +不了解的朋友一定要好好看一下,学完马上就可以实践到项目上去。 + +并且,本文示例项目使用的是目前最新的 Spring Boot 版本 2.4.5!(截止到 2021-04-21) + +示例项目源代码地址:[https://github.com/CodingDocs/springboot-guide/tree/master/source-code/bean-validation-demo](https://github.com/CodingDocs/springboot-guide/tree/master/source-code/bean-validation-demo) 。 + +## 添加相关依赖 + +如果开发普通 Java 程序的的话,你需要可能需要像下面这样依赖: + +```xml + + org.hibernate.validator + hibernate-validator + 6.0.9.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.6 + +``` + +不过,相信大家都是使用的 Spring Boot 框架来做开发。 + +基于 Spring Boot 的话,就比较简单了,只需要给项目添加上 `spring-boot-starter-web` 依赖就够了,它的子依赖包含了我们所需要的东西。另外,我们的示例项目中还使用到了 Lombok。 + +![](https://img-blog.csdnimg.cn/20210421172058450.png) + +```xml + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + true + + + junit + junit + 4.13.1 + test + + + org.springframework.boot + spring-boot-starter-test + test + + +``` + +但是!!! Spring Boot 2.3 1 之后,`spring-boot-starter-validation` 已经不包括在了 `spring-boot-starter-web` 中,需要我们手动加上! + +![](https://img-blog.csdnimg.cn/20210421170846695.png) + +```xml + + org.springframework.boot + spring-boot-starter-validation + +``` + +## 验证 Controller 的输入 + +### 验证请求体 + +验证请求体即使验证被 `@RequestBody` 注解标记的方法参数。 + +**`PersonController`** + +我们在需要验证的参数上加上了`@Valid`注解,如果验证失败,它将抛出`MethodArgumentNotValidException`。默认情况下,Spring 会将此异常转换为 HTTP Status 400(错误请求)。 + +```java +@RestController +@RequestMapping("/api/person") +@Validated +public class PersonController { + + @PostMapping + public ResponseEntity save(@RequestBody @Valid PersonRequest personRequest) { + return ResponseEntity.ok().body(personRequest); + } +} +``` + +**`PersonRequest`** + +我们使用校验注解对请求的参数进行校验! + +```java +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PersonRequest { + + @NotNull(message = "classId 不能为空") + private String classId; + + @Size(max = 33) + @NotNull(message = "name 不能为空") + private String name; + + @Pattern(regexp = "(^Man$|^Woman$|^UGM$)", message = "sex 值不在可选范围") + @NotNull(message = "sex 不能为空") + private String sex; + +} + +``` + +正则表达式说明: + +- `^string` : 匹配以 string 开头的字符串 +- `string$` :匹配以 string 结尾的字符串 +- `^string$` :精确匹配 string 字符串 +- `(^Man$|^Woman$|^UGM$)` : 值只能在 Man,Woman,UGM 这三个值中选择 + +**`GlobalExceptionHandler`** + +自定义异常处理器可以帮助我们捕获异常,并进行一些简单的处理。如果对于下面的处理异常的代码不太理解的话,可以查看这篇文章 [《SpringBoot 处理异常的几种常见姿势》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247485568&idx=2&sn=c5ba880fd0c5d82e39531fa42cb036ac&chksm=cea2474bf9d5ce5dcbc6a5f6580198fdce4bc92ef577579183a729cb5d1430e4994720d59b34&token=1924773784&lang=zh_CN#rd)。 + +```java +@ControllerAdvice(assignableTypes = {PersonController.class}) +public class GlobalExceptionHandler { + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationExceptions( + MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); + } +} +``` + +**通过测试验证** + +下面我通过 `MockMvc` 模拟请求 `Controller` 的方式来验证是否生效。当然了,你也可以通过 `Postman` 这种工具来验证。 + +```java +@SpringBootTest +@AutoConfigureMockMvc +public class PersonControllerTest { + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + /** + * 验证出现参数不合法的情况抛出异常并且可以正确被捕获 + */ + @Test + public void should_check_person_value() throws Exception { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + mockMvc.perform(post("/api/personRequest") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) + .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围")) + .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空")); + } +} +``` + +**使用 `Postman` 验证** + +![](https://img-blog.csdnimg.cn/20210421175345253.png) + +### 验证请求参数 + +验证请求参数(Path Variables 和 Request Parameters)即是验证被 `@PathVariable` 以及 `@RequestParam` 标记的方法参数。 + +**`PersonController`** + +**一定一定不要忘记在类上加上 `Validated` 注解了,这个参数可以告诉 Spring 去校验方法参数。** + +```java +@RestController +@RequestMapping("/api/persons") +@Validated +public class PersonController { + + @GetMapping("/{id}") + public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5, message = "超过 id 的范围了") Integer id) { + return ResponseEntity.ok().body(id); + } + + @PutMapping + public ResponseEntity getPersonByName(@Valid @RequestParam("name") @Size(max = 6, message = "超过 name 的范围了") String name) { + return ResponseEntity.ok().body(name); + } +} +``` + +**`ExceptionHandler`** + +```java + @ExceptionHandler(ConstraintViolationException.class) + ResponseEntity handleConstraintViolationException(ConstraintViolationException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); + } +``` + +**通过测试验证** + +```java +@Test +public void should_check_path_variable() throws Exception { + mockMvc.perform(get("/api/person/6") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("getPersonByID.id: 超过 id 的范围了")); +} + +@Test +public void should_check_request_param_value2() throws Exception { + mockMvc.perform(put("/api/person") + .param("name", "snailclimbsnailclimb") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("getPersonByName.name: 超过 name 的范围了")); +} +``` + +**使用 `Postman` 验证** + +![](https://img-blog.csdnimg.cn/20210421190508416.png) + +![](https://img-blog.csdnimg.cn/20210421190810975.png) + +## 验证 Service 中的方法 + +我们还可以验证任何 Spring Bean 的输入,而不仅仅是 `Controller` 级别的输入。通过使用`@Validated`和`@Valid`注释的组合即可实现这一需求! + +一般情况下,我们在项目中也更倾向于使用这种方案。 + +**一定一定不要忘记在类上加上 `Validated` 注解了,这个参数可以告诉 Spring 去校验方法参数。** + +```java +@Service +@Validated +public class PersonService { + + public void validatePersonRequest(@Valid PersonRequest personRequest) { + // do something + } + +} +``` + +**通过测试验证:** + +```java +@RunWith(SpringRunner.class) +@SpringBootTest +public class PersonServiceTest { + @Autowired + private PersonService service; + + @Test + public void should_throw_exception_when_person_request_is_not_valid() { + try { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + service.validatePersonRequest(personRequest); + } catch (ConstraintViolationException e) { + // 输出异常信息 + e.getConstraintViolations().forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); + } + } +} +``` + +输出结果如下: + +``` +name 不能为空 +sex 值不在可选范围 +``` + +## Validator 编程方式手动进行参数验证 + +某些场景下可能会需要我们手动校验并获得校验结果。 + +我们通过 `Validator` 工厂类获得的 `Validator` 示例。另外,如果是在 Spring Bean 中的话,还可以通过 `@Autowired` 直接注入的方式。 + +```java +@Autowired +Validator validate +``` + +具体使用情况如下: + +```java +/** + * 手动校验对象 + */ +@Test +public void check_person_manually() { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + Set> violations = validator.validate(personRequest); + violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); +} +``` + +输出结果如下: + +``` +sex 值不在可选范围 +name 不能为空 +``` + +## 自定义 Validator(实用) + +如果自带的校验注解无法满足你的需求的话,你还可以自定义实现注解。 + +### 案例一:校验特定字段的值是否在可选范围 + +比如我们现在多了这样一个需求:`PersonRequest` 类多了一个 `Region` 字段,`Region` 字段只能是`China`、`China-Taiwan`、`China-HongKong`这三个中的一个。 + +**第一步,你需要创建一个注解 `Region`。** + +```java +@Target({FIELD}) +@Retention(RUNTIME) +@Constraint(validatedBy = RegionValidator.class) +@Documented +public @interface Region { + + String message() default "Region 值不在可选范围内"; + + Class[] groups() default {}; + + Class[] payload() default {}; +} +``` + +**第二步,你需要实现 `ConstraintValidator`接口,并重写`isValid` 方法。** + +```java +public class RegionValidator implements ConstraintValidator { + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + HashSet regions = new HashSet<>(); + regions.add("China"); + regions.add("China-Taiwan"); + regions.add("China-HongKong"); + return regions.contains(value); + } +} + +``` + +现在你就可以使用这个注解: + +```java +@Region +private String region; +``` + +**通过测试验证** + +```java +PersonRequest personRequest = PersonRequest.builder() + .region("Shanghai").build(); +mockMvc.perform(post("/api/person") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) + .andExpect(MockMvcResultMatchers.jsonPath("region").value("Region 值不在可选范围内")); +``` + +**使用 `Postman` 验证** + +![](https://img-blog.csdnimg.cn/20210421203330978.png) + +### 案例二:校验电话号码 + +校验我们的电话号码是否合法,这个可以通过正则表达式来做,相关的正则表达式都可以在网上搜到,你甚至可以搜索到针对特定运营商电话号码段的正则表达式。 + +`PhoneNumber.java` + +```java +@Documented +@Constraint(validatedBy = PhoneNumberValidator.class) +@Target({FIELD, PARAMETER}) +@Retention(RUNTIME) +public @interface PhoneNumber { + String message() default "Invalid phone number"; + Class[] groups() default {}; + Class[] payload() default {}; +} +``` + +`PhoneNumberValidator.java` + +```java +public class PhoneNumberValidator implements ConstraintValidator { + + @Override + public boolean isValid(String phoneField, ConstraintValidatorContext context) { + if (phoneField == null) { + // can be null + return true; + } + // 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 + // ^ 匹配输入字符串开始的位置 + // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d + // $ 匹配输入字符串结尾的位置 + String regExp = "^[1]((3[0-9])|(4[5-9])|(5[0-3,5-9])|([6][5,6])|(7[0-9])|(8[0-9])|(9[1,8,9]))\\d{8}$"; + return phoneField.matches(regExp); + } +} + +``` + +搞定,我们现在就可以使用这个注解了。 + +```java +@PhoneNumber(message = "phoneNumber 格式不正确") +@NotNull(message = "phoneNumber 不能为空") +private String phoneNumber; +``` + +**通过测试验证** + +```java +PersonRequest personRequest = PersonRequest.builder() + .phoneNumber("1816313815").build(); +mockMvc.perform(post("/api/person") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) + .andExpect(MockMvcResultMatchers.jsonPath("phoneNumber").value("phoneNumber 格式不正确")); +``` + +![](https://img-blog.csdnimg.cn/20210421204116640.png) + +## 使用验证组 + +验证组我们基本是不会用到的,也不太建议在项目中使用,理解起来比较麻烦,写起来也比较麻烦。简单了解即可! + +当我们对对象操作的不同方法有不同的验证规则的时候才会用到验证组。 + +我写一个简单的例子,你们就能看明白了! + +**1.先创建两个接口,代表不同的验证组** + +```java +public interface AddPersonGroup { +} +public interface DeletePersonGroup { +} +``` + +**2.使用验证组** + +```java +@Data +public class Person { + // 当验证组为 DeletePersonGroup 的时候 group 字段不能为空 + @NotNull(groups = DeletePersonGroup.class) + // 当验证组为 AddPersonGroup 的时候 group 字段需要为空 + @Null(groups = AddPersonGroup.class) + private String group; +} + +@Service +@Validated +public class PersonService { + + @Validated(AddPersonGroup.class) + public void validatePersonGroupForAdd(@Valid Person person) { + // do something + } + + @Validated(DeletePersonGroup.class) + public void validatePersonGroupForDelete(@Valid Person person) { + // do something + } + +} +``` + +通过测试验证: + +```java + @Test(expected = ConstraintViolationException.class) + public void should_check_person_with_groups() { + Person person = new Person(); + person.setGroup("group1"); + service.validatePersonGroupForAdd(person); + } + + @Test(expected = ConstraintViolationException.class) + public void should_check_person_with_groups2() { + Person person = new Person(); + service.validatePersonGroupForDelete(person); + } +``` + +验证组使用下来的体验就是有点反模式的感觉,让代码的可维护性变差了!尽量不要使用! + +## 常用校验注解总结 + +`JSR303` 定义了 `Bean Validation`(校验)的标准 `validation-api`,并没有提供实现。`Hibernate Validation`是对这个规范/规范的实现 `hibernate-validator`,并且增加了 `@Email`、`@Length`、`@Range` 等注解。`Spring Validation` 底层依赖的就是`Hibernate Validation`。 + +**JSR 提供的校验注解**: + +- `@Null` 被注释的元素必须为 null +- `@NotNull` 被注释的元素必须不为 null +- `@AssertTrue` 被注释的元素必须为 true +- `@AssertFalse` 被注释的元素必须为 false +- `@Min(value)` 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 +- `@Max(value)` 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 +- `@DecimalMin(value)` 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 +- `@DecimalMax(value)` 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 +- `@Size(max=, min=)` 被注释的元素的大小必须在指定的范围内 +- `@Digits (integer, fraction)` 被注释的元素必须是一个数字,其值必须在可接受的范围内 +- `@Past` 被注释的元素必须是一个过去的日期 +- `@Future` 被注释的元素必须是一个将来的日期 +- `@Pattern(regex=,flag=)` 被注释的元素必须符合指定的正则表达式 + +**Hibernate Validator 提供的校验注解**: + +- `@NotBlank(message =)` 验证字符串非 null,且长度必须大于 0 +- `@Email` 被注释的元素必须是电子邮箱地址 +- `@Length(min=,max=)` 被注释的字符串的大小必须在指定的范围内 +- `@NotEmpty` 被注释的字符串的必须非空 +- `@Range(min=,max=,message=)` 被注释的元素必须在合适的范围内 + +## 拓展 + +经常有小伙伴问到:“`@NotNull` 和 `@Column(nullable = false)` 两者有什么区别?” + +我这里简单回答一下: + +- `@NotNull`是 JSR 303 Bean 验证批注,它与数据库约束本身无关。 +- `@Column(nullable = false)` : 是 JPA 声明列为非空的方法。 + +总结来说就是即前者用于验证,而后者则用于指示数据库创建表的时候对表的约束。 diff --git a/docs/start/springboot-hello-world.md b/docs/start/springboot-hello-world.md index 78ae5cb..9d6d49a 100644 --- a/docs/start/springboot-hello-world.md +++ b/docs/start/springboot-hello-world.md @@ -1,22 +1,26 @@ -### 新建 Spring Boot 项目常用的两种方式 +示例项目源代码地址:[https://github.com/CodingDocs/springboot-guide/tree/master/source-code/hello-world](https://github.com/CodingDocs/springboot-guide/tree/master/source-code/hello-world) 。 -你可以通过 https://start.spring.io/ 这个网站来生成一个 Spring Boot 的项目。 +## 新建 Spring Boot 项目 -![start.spring.io](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/spring.start.io.png) +**1. 你可以通过 [https://start.spring.io/](https://start.spring.io/) 这个网站来生成一个 Spring Boot 的项目。** + +![start.spring.io](https://img-blog.csdnimg.cn/img_convert/69f88b648b5f94fe8fa509fc4d987057.png) 注意勾选上 Spring Web 这个模块,这是我们所必需的一个依赖。当所有选项都勾选完毕之后,点击下方的按钮 Generate 下载这个 Spring Boot 的项目。下载完成并解压之后,我们直接使用 IDEA 打开即可。 -当然你也可以直接通过 IDEA 来生成一个 Spring Boot 的项目,具体方法和上面类似:`File->New->Project->Spring Initializr`。 +另外,阿里也有一个类似的网站 [https://start.aliyun.com/bootstrap.html](https://start.aliyun.com/bootstrap.html) ,功能甚至还要更强大点,支持生成特定应用架构的项目模板! -### Spring Boot 项目结构分析 +![](https://img-blog.csdnimg.cn/20210421220259726.png) -成功打开项目之后,项目长下面这个样子: +**2.你也可以直接通过 IDEA 来生成一个 Spring Boot 的项目,具体方法和上面类似:`File->New->Project->Spring Initializr`。** - +## Spring Boot 项目结构分析 +成功打开项目之后,项目长下面这个样子: +![](https://img-blog.csdnimg.cn/img_convert/1f1a3ee40347e941891988cbb72ceee1.png#pic_center) -以 Application为后缀名的 Java 类一般就是 Spring Boot 的启动类,比如本项目的启动项目就是`HelloWorldApplication` 。我们直接像运行普通 Java 程序一样运行它,由于 Spring Boot 本身就嵌入servlet容器的缘故,我们的 web 项目就运行成功了, 非常方便。 +以 Application 为后缀名的 Java 类一般就是 Spring Boot 的启动类,比如本项目的启动项目就是`HelloWorldApplication` 。我们直接像运行普通 Java 程序一样运行它,由于 Spring Boot 本身就嵌入 servlet 容器的缘故,我们的 web 项目就运行成功了, 非常方便。 需要注意的一点是 **Spring Boot 的启动类是需要最外层的,不然可能导致一些类无法被正确扫描到,导致一些奇怪的问题。** 一般情况下 Spring Boot 项目结构类似下面这样 @@ -35,19 +39,19 @@ com | +- controller | +- CustomerController.java - | - | +- config + | + +- config | +- swagerConfig.java | ``` -1. ` Application.java`是项目的启动类 -2. domain目录主要用于实体(Entity)与数据访问层(Repository) +1. `Application.java`是项目的启动类 +2. domain 目录主要用于实体(Entity)与数据访问层(Repository) 3. service 层主要是业务类代码 4. controller 负责页面访问控制 5. config 目录主要放一些配置类 -### @SpringBootApplication 注解分析 +## @SpringBootApplication 注解分析 `HelloWorldApplication` @@ -91,21 +95,21 @@ public @interface SpringBootConfiguration { } ``` -可以看出大概可以把 `@SpringBootApplication `看作是 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan ` 注解的集合。根据 SpringBoot官网,这三个注解的作用分别是: +可以看出大概可以把 `@SpringBootApplication`看作是 `@Configuration`、`@EnableAutoConfiguration`、`@ComponentScan` 注解的集合。根据 SpringBoot 官网,这三个注解的作用分别是: - `@EnableAutoConfiguration`:启用 SpringBoot 的自动配置机制 -- `@ComponentScan`: 扫描被`@Component` (`@Service`,`@Controller`)注解的bean,注解默认会扫描该类所在的包下所有的类。 -- `@Configuration`:允许在上下文中注册额外的bean或导入其他配置类。 +- `@ComponentScan`: 扫描被`@Component` (`@Service`,`@Controller`)注解的 bean,注解默认会扫描该类所在的包下所有的类。 +- `@Configuration`:允许在上下文中注册额外的 bean 或导入其他配置类。 -所以说 `@SpringBootApplication `就是几个重要的注解的组合,为什么要有它?当然是为了省事,避免了我们每次开发 Spring Boot 项目都要写一些必备的注解。这一点在我们平时开发中也经常用到,比如我们通常会提一个测试基类,这个基类包含了我们写测试所需要的一些基本的注解和一些依赖。 +所以说 `@SpringBootApplication`就是几个重要的注解的组合,为什么要有它?当然是为了省事,避免了我们每次开发 Spring Boot 项目都要写一些必备的注解。这一点在我们平时开发中也经常用到,比如我们通常会提一个测试基类,这个基类包含了我们写测试所需要的一些基本的注解和一些依赖。 -### 新建一个 Controller +## 新建一个 Controller 上面说了这么多,我们现在正式开始写 Spring Boot 版的 “Hello World” 吧。 -新建一个 controller 文件夹,并在这个文件夹下新建一个名字叫做 `HelloWorldController` 的类。 +新建一个 `controller` 文件夹,并在这个文件夹下新建一个名字叫做 `HelloWorldController` 的类。 -`@RestController`是Spring 4 之后新加的注解,如果在Spring4之前开发 RESTful Web服务的话,你需要使用`@Controller` 并结合`@ResponseBody`注解,也就是说`@Controller` +`@ResponseBody`= `@RestController`。对于这两个注解,我在基础篇单独抽了一篇文章来介绍。 +`@RestController`是 Spring 4 之后新加的注解,如果在 Spring4 之前开发 RESTful Web 服务的话,你需要使用`@Controller` 并结合`@ResponseBody`注解,也就是说`@Controller` +`@ResponseBody`= `@RestController`。对于这两个注解,我在基础篇单独抽了一篇文章来介绍。 `com.example.helloworld.controller` @@ -134,9 +138,9 @@ public class HelloWorldController { server.port=8333 ``` -### 大功告成,运行项目 +## 大功告成,运行项目 -运行 `HelloWorldApplication` ,运行成功控制台会打印出一些消息,不要忽略这些消息,它里面会有一些比较有用的信息。 +运行 `HelloWorldApplication` ,运行成功控制台会打印出一些消息,不要忽略这些消息,它里面会有一些比较有用的信息。 ``` 2019-10-03 09:24:47.757 INFO 26326 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8333 (http) with context path '' @@ -146,14 +150,6 @@ server.port=8333 浏览器 http://localhost:8333/test/hello 如果你可以在页面正确得到 "Hello World" 的话,说明你已经成功完成了这部分内容。 -### 总结 - -通过本文我们学到了如何新建 Spring Boot 项目、SpringBoot 项目常见的项目结构分析、`@SpringBootApplication` 注解分析,最后实现了 Spring Boot 版的 "Hello World"。 - -代码地址: https://github.com/Snailclimb/springboot-guide/tree/master/source-code/start/hello-world(建议自己手敲一遍!!!) - -### 代办 - -- [ ] Spring Boot 启动流程分析 +## 总结 - \ No newline at end of file +通过本文我们学到了如何新建 Spring Boot 项目、SpringBoot 项目常见的项目结构分析、`@SpringBootApplication` 注解分析,最后实现了 Spring Boot 版的 "Hello World"。 \ No newline at end of file diff --git a/docs/start/springboot-introduction.md b/docs/start/springboot-introduction.md index 8b1e792..a6c73f6 100644 --- a/docs/start/springboot-introduction.md +++ b/docs/start/springboot-introduction.md @@ -1,43 +1,69 @@ -# 一 SpringBoot介绍 +## 1.SpringBoot 介绍 -## 1.1 先从Spring谈起 -我们知道Spring是重量级企业开发框架 **Enterprise JavaBean(EJB)** 的替代品,Spring为企业级Java开发提供了一种相对简单的方法,通过 **依赖注入** 和 **面向切面编程** ,用简单的 **Java对象(Plain Old Java Object,POJO)** 实现了EJB的功能 +### 1.1 先从 Spring 谈起 -**虽然Spring的组件代码是轻量级的,但它的配置却是重量级的(需要大量XML配置)** 。Spring 2.5引入了基于注解的组件扫描,这消除了大量针对应用程序自身组件的显式XML配置。Spring 3.0引入了基于Java的配置,这是一种类型安全的可重构配置方式,可以代替XML。 +Spring 是重量级企业开发框架 **Enterprise JavaBean(EJB)** 的替代品,Spring 为企业级 Java 开发提供了一种相对简单的方法,通过 **依赖注入** 和 **面向切面编程** ,用简单的 **Java 对象(Plain Old Java Object,POJO)** 实现了 EJB 的功能 -尽管如此,我们依旧没能逃脱配置的魔爪。开启某些Spring特性时,比如事务管理和Spring MVC,还是需要用XML或Java进行显式配置。启用第三方库时也需要显式配置,比如基于Thymeleaf的Web视图。配置Servlet和过滤器(比如Spring的DispatcherServlet)同样需要在web.xml或Servlet初始化代码里进行显式配置。组件扫描减少了配置量,Java配置让它看上去简洁不少,但Spring还是需要不少配置。 +**虽然 Spring 的组件代码是轻量级的,但它的配置却是重量级的(需要大量 XML 配置)** 。 -光配置这些XML文件都够我们头疼的了,占用了我们大部分时间和精力。除此之外,相关库的依赖非常让人头疼,不同库之间的版本冲突也非常常见。 +为此,Spring 2.5 引入了基于注解的组件扫描,这消除了大量针对应用程序自身组件的显式 XML 配置。Spring 3.0 引入了基于 Java 的配置,这是一种类型安全的可重构配置方式,可以代替 XML。 -**不过,好消息是:Spring Boot让这一切成为了过去。** +尽管如此,我们依旧没能逃脱配置的魔爪。开启某些 Spring 特性时,比如事务管理和 Spring MVC,还是需要用 XML 或 Java 进行显式配置。启用第三方库时也需要显式配置,比如基于 Thymeleaf 的 Web 视图。配置 Servlet 和过滤器(比如 Spring 的`DispatcherServlet`)同样需要在 web.xml 或 Servlet 初始化代码里进行显式配置。组件扫描减少了配置量,Java 配置让它看上去简洁不少,但 Spring 还是需要不少配置。 -## 1.2 再来谈谈 Spring Boot +光配置这些 XML 文件都够我们头疼的了,占用了我们大部分时间和精力。除此之外,相关库的依赖非常让人头疼,不同库之间的版本冲突也非常常见。 +**不过,好消息是:Spring Boot 让这一切成为了过去。** + +### 1.2 再来谈谈 Spring Boot **最好直白的介绍莫过于官方的介绍:** -> Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”...Most Spring Boot applications need very little Spring configuration.(Spring Boot可以轻松创建独立的生产级基于Spring的应用程序,只要通过 “just run”(可能是run ‘Application’或java -jar 或 tomcat 或 maven插件run 或 shell脚本)便可以运行项目。大部分Spring Boot项目只需要少量的配置即可) +> Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”...Most Spring Boot applications need very little Spring configuration.(Spring Boot 可以轻松创建独立的生产级基于 Spring 的应用程序,只要通过 “just run”(可能是 run ‘Application’或 java -jar 或 tomcat 或 maven 插件 run 或 shell 脚本)便可以运行项目。大部分 Spring Boot 项目只需要少量的配置即可) -**简而言之,从本质上来说,Spring Boot就是Spring,它做了那些没有它你自己也会去做的Spring Bean配置。** +**简而言之,从本质上来说,Spring Boot 就是 Spring,它做了那些没有它你自己也会去做的 Spring Bean 配置。** -### 1.2.1 为什么需要 Spring Boot? +#### 1.2.1 为什么需要 Spring Boot? -Spring Framework旨在简化J2EE企业应用程序开发。Spring Boot Framework旨在简化Spring开发。 +Spring Framework 旨在简化 J2EE 企业应用程序开发。Spring Boot Framework 旨在简化 Spring 开发。 ![why-we-need-springboot](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/why-we-need-springboot.png) -### 1.2.2 Spring Boot的主要优点 +#### 1.2.2 Spring Boot 的主要优点 1. 开发基于 Spring 的应用程序很容易。 2. Spring Boot 项目所需的开发或工程时间明显减少,通常会提高整体生产力。 -3. Spring Boot不需要编写大量样板代码、XML配置和注释。 -4. Spring引导应用程序可以很容易地与Spring生态系统集成,如Spring JDBC、Spring ORM、Spring Data、Spring Security等。 -5. Spring Boot遵循“固执己见的默认配置”,以减少开发工作(默认配置可以修改)。 -6. Spring Boot 应用程序提供嵌入式HTTP服务器,如Tomcat和Jetty,可以轻松地开发和测试web应用程序。(这点很赞!普通运行Java程序的方式就能运行基于Spring Boot web 项目,省事很多) -7. Spring Boot提供命令行接口(CLI)工具,用于开发和测试Spring Boot应用程序,如Java或Groovy。 -8. Spring Boot提供了多种插件,可以使用内置工具(如Maven和Gradle)开发和测试Spring Boot应用程序。 +3. Spring Boot 不需要编写大量样板代码、XML 配置和注释。 +4. Spring 引导应用程序可以很容易地与 Spring 生态系统集成,如 Spring JDBC、Spring ORM、Spring Data、Spring Security 等。 +5. Spring Boot 遵循“固执己见的默认配置”,以减少开发工作(默认配置可以修改)。 +6. Spring Boot 应用程序提供嵌入式 HTTP 服务器,如 Tomcat 和 Jetty,可以轻松地开发和测试 web 应用程序。(这点很赞!普通运行 Java 程序的方式就能运行基于 Spring Boot web 项目,省事很多) +7. Spring Boot 提供命令行接口(CLI)工具,用于开发和测试 Spring Boot 应用程序,如 Java 或 Groovy。 +8. Spring Boot 提供了多种插件,可以使用内置工具(如 Maven 和 Gradle)开发和测试 Spring Boot 应用程序。 + +## 2.SpringBoot 开发环境要求 + +### 2.1 构建工具 + +构建工具(本项目涉及的代码大部分会采用 Maven 作为包管理工具): + +| **Build Tool** | **Version** | +| -------------- | ----------- | +| Maven | 3.3+ | +| Gradle | 4.4+ | + +### 2.2 开发工具推荐 + +推荐使用 IDEA 进行开发。最好的 Java 后台开发编辑器,没有之一! +### 2.3 Web 服务器 +Spring Boot 支持以下嵌入式 servlet 容器: +| **Name** | **Servlet Version** | +| ------------ | ------------------- | +| Tomcat 9.0 | 4.0 | +| Jetty 9.4 | 3.1 | +| Undertow 2.0 | 4.0 | +您还可以将 Spring 引导应用程序部署到任何 Servlet 3.1+兼容的 Web 容器中。 +这就是你为什么可以通过直接像运行 普通 Java 项目一样运行 SpringBoot 项目。这样的确省事了很多,方便了我们进行开发,降低了学习难度。 \ No newline at end of file diff --git a/docs/start/springboot-system-requirements.md b/docs/start/springboot-system-requirements.md deleted file mode 100644 index df55803..0000000 --- a/docs/start/springboot-system-requirements.md +++ /dev/null @@ -1,30 +0,0 @@ -### JDK - -截止到目前Spring Boot 的最新版本:2.1.8.RELEASE 要求 JDK 版本在 1.8 以上,所以确保你的电脑已经正确下载安装配置了 JDK(推荐 JDK 1.8 版本)。 - -### 构建工具 - -构建工具(本项目涉及的代码大部分会采用 Maven 作为包管理工具): - -| **Build Tool** | **Version** | -| -------------- | ----------- | -| Maven | 3.3+ | -| Gradle | 4.4+ | - -### 开发工具推荐 - -推荐使用 IDEA 进行开发。最好的 Java 后台开发编辑器,没有之一! - -### Web 服务器 - -Spring Boot支持以下嵌入式servlet容器: - -| **Name** | **Servlet Version** | -| ------------ | ------------------- | -| Tomcat 9.0 | 4.0 | -| Jetty 9.4 | 3.1 | -| Undertow 2.0 | 4.0 | - -您还可以将Spring引导应用程序部署到任何Servlet 3.1+兼容的 Web 容器中。 - -这就是你为什么可以通过直接像运行 普通 Java 项目一样运行 SpringBoot 项目。这样的确省事了很多,方便了我们进行开发,降低了学习难度。 \ No newline at end of file diff --git a/source-code/advanced/bean-validation-demo/pom.xml b/source-code/advanced/bean-validation-demo/pom.xml index d5779cb..c5a9e2f 100644 --- a/source-code/advanced/bean-validation-demo/pom.xml +++ b/source-code/advanced/bean-validation-demo/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.1.8.RELEASE + 2.4.5 com.example @@ -19,22 +19,25 @@ - org.springframework.boot spring-boot-starter-web org.springframework.boot - spring-boot-devtools - runtime - true + spring-boot-starter-validation org.projectlombok lombok true + + junit + junit + 4.13.1 + test + org.springframework.boot spring-boot-starter-test diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/.DS_Store b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/.DS_Store deleted file mode 100644 index feb1863..0000000 Binary files a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/.DS_Store and /dev/null differ diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java index 1b22d08..c0482b5 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java @@ -1,12 +1,9 @@ package com.example.beanvalidationdemo.controller; -import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; import org.springframework.http.ResponseEntity; -import org.springframework.validation.BindingResult; -import org.springframework.validation.Errors; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.Mapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; @@ -20,21 +17,21 @@ import javax.validation.constraints.Size; @RestController -@RequestMapping("/api") +@RequestMapping("/api/persons") @Validated public class PersonController { - @PostMapping("/person") - public ResponseEntity getPerson(@RequestBody @Valid Person person) { - return ResponseEntity.ok().body(person); + @PostMapping + public ResponseEntity save(@RequestBody @Valid PersonRequest personRequest) { + return ResponseEntity.ok().body(personRequest); } - @GetMapping("/person/{id}") + @GetMapping("/{id}") public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5, message = "超过 id 的范围了") Integer id) { return ResponseEntity.ok().body(id); } - @PutMapping("/person") + @PutMapping public ResponseEntity getPersonByName(@Valid @RequestParam("name") @Size(max = 6, message = "超过 name 的范围了") String name) { return ResponseEntity.ok().body(name); } diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java index d095320..80bb5e8 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java @@ -1,48 +1,18 @@ package com.example.beanvalidationdemo.entity; -import com.example.beanvalidationdemo.constants.Constants; import com.example.beanvalidationdemo.service.AddPersonGroup; import com.example.beanvalidationdemo.service.DeletePersonGroup; -import com.example.beanvalidationdemo.validation.PhoneNumber; -import com.example.beanvalidationdemo.validation.Region; -import lombok.AllArgsConstructor; import lombok.Data; -import lombok.NoArgsConstructor; -import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; @Data -@AllArgsConstructor -@NoArgsConstructor public class Person { - @NotNull(message = "classId 不能为空") - private String classId; - - @Size(max = 33) - @NotNull(message = "name 不能为空") - private String name; - - @Pattern(regexp = Constants.sexs, message = "sex 值不在可选范围") - @NotNull(message = "sex 不能为空") - private String sex; - - @Email(message = "email 格式不正确") - @NotNull(message = "email 不能为空") - private String email; - - @PhoneNumber(message = "phoneNumber 格式不正确") - @NotNull(message = "phoneNumber 不能为空") - private String phoneNumber; - - @Region - private String region; - + // 当验证组为 DeletePersonGroup 的时候 group 字段不能为空 @NotNull(groups = DeletePersonGroup.class) + // 当验证组为 AddPersonGroup 的时候 group 字段需要为空 @Null(groups = AddPersonGroup.class) private String group; } diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java new file mode 100644 index 0000000..9b2c789 --- /dev/null +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java @@ -0,0 +1,44 @@ +package com.example.beanvalidationdemo.entity; + +import com.example.beanvalidationdemo.validation.PhoneNumber; +import com.example.beanvalidationdemo.validation.Region; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/04/21 20:48 + **/ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PersonRequest { + + @NotNull(message = "classId 不能为空") + private String classId; + + @Size(max = 33) + @NotNull(message = "name 不能为空") + private String name; + + @Pattern(regexp = "(^Man$|^Woman$|^UGM$)", message = "sex 值不在可选范围") + @NotNull(message = "sex 不能为空") + private String sex; + + @Region + private String region; + + @PhoneNumber(message = "phoneNumber 格式不正确") + @NotNull(message = "phoneNumber 不能为空") + private String phoneNumber; + +} diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java index 99856bf..08e8e14 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java @@ -1,6 +1,7 @@ package com.example.beanvalidationdemo.service; import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; @@ -10,7 +11,7 @@ @Validated public class PersonService { - public void validatePerson(@Valid Person person) { + public void validatePersonRequest(@Valid PersonRequest personRequest) { // do something } diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java index 8226e99..afd5373 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java @@ -15,6 +15,8 @@ @Retention(RUNTIME) public @interface PhoneNumber { String message() default "Invalid phone number"; + Class[] groups() default {}; + Class[] payload() default {}; } diff --git a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java index 4fc63c9..85acdcd 100644 --- a/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java +++ b/source-code/advanced/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java @@ -3,7 +3,7 @@ import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -public class PhoneNumberValidator implements ConstraintValidator { +public class PhoneNumberValidator implements ConstraintValidator { @Override public boolean isValid(String phoneField, ConstraintValidatorContext context) { @@ -11,6 +11,11 @@ public boolean isValid(String phoneField, ConstraintValidatorContext context) { // can be null return true; } - return phoneField.matches("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$") && phoneField.length() > 8 && phoneField.length() < 14; + // 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 + // ^ 匹配输入字符串开始的位置 + // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d + // $ 匹配输入字符串结尾的位置 + String regExp = "^[1]((3[0-9])|(4[5-9])|(5[0-3,5-9])|([6][5,6])|(7[0-9])|(8[0-9])|(9[1,8,9]))\\d{8}$"; + return phoneField.matches(regExp); } } diff --git a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/HelloWorldControllerTest.java b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/HelloWorldControllerTest.java deleted file mode 100644 index ea998ca..0000000 --- a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/HelloWorldControllerTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.example.beanvalidationdemo; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; - -/** - * 验证基本的项目基本环境是否有问题 - */ -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class HelloWorldControllerTest { - @Autowired - private MockMvc mockMvc; - - @Test - public void should_get_hello() throws Exception { - mockMvc.perform(get("/api/hello")).andExpect(content().string("Hello")); - } -} diff --git a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java index 0ff4eb4..f020f05 100644 --- a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java +++ b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java @@ -1,15 +1,13 @@ package com.example.beanvalidationdemo; -import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @@ -25,7 +23,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class PersonControllerTest { @@ -35,85 +32,52 @@ public class PersonControllerTest { @Autowired private ObjectMapper objectMapper; - @Test - public void should_get_person() throws Exception { - Person person = new Person(); - person.setName("SnailClimb"); - person.setSex("Man"); - person.setClassId("82938390"); - person.setEmail("Snailclimb@qq.com"); - person.setRegion("China"); - person.setPhoneNumber("13615833391"); - - - mockMvc.perform(post("/api/person") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(person))) - .andExpect(MockMvcResultMatchers.jsonPath("name").value("SnailClimb")) - .andExpect(MockMvcResultMatchers.jsonPath("classId").value("82938390")) - .andExpect(MockMvcResultMatchers.jsonPath("sex").value("Man")) - .andExpect(MockMvcResultMatchers.jsonPath("email").value("Snailclimb@qq.com")); - ; - } + /** + * 验证出现参数不合法的情况抛出异常并且可以正确被捕获 + */ @Test public void should_check_person_value() throws Exception { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - person.setRegion("BeiGuo"); - person.setPhoneNumber("1361583339"); - + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390") + .region("Shanghai") + .phoneNumber("1816313815").build(); mockMvc.perform(post("/api/person") - .contentType(MediaType.APPLICATION_JSON_UTF8) - .content(objectMapper.writeValueAsString(person))) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围")) .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空")) - .andExpect(MockMvcResultMatchers.jsonPath("email").value("email 格式不正确")) .andExpect(MockMvcResultMatchers.jsonPath("region").value("Region 值不在可选范围内")) .andExpect(MockMvcResultMatchers.jsonPath("phoneNumber").value("phoneNumber 格式不正确")); - } @Test - public void should_check_param_value() throws Exception { - + public void should_check_path_variable() throws Exception { mockMvc.perform(get("/api/person/6") - .contentType(MediaType.APPLICATION_JSON_UTF8)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(content().string("getPersonByID.id: 超过 id 的范围了")); } @Test - public void should_check_param_value2() throws Exception { - + public void should_check_request_param_value2() throws Exception { mockMvc.perform(put("/api/person") .param("name", "snailclimbsnailclimb") - .contentType(MediaType.APPLICATION_JSON_UTF8)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(content().string("getPersonByName.name: 超过 name 的范围了")); } /** - * 手动校验对象,很多场景下需要使用这种方式 + * 手动校验对象 */ @Test public void check_person_manually() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - Set> violations = validator.validate(person); - //output: - //email 格式不正确 - //name 不能为空 - //sex 值不在可选范围 - for (ConstraintViolation constraintViolation : violations) { - System.out.println(constraintViolation.getMessage()); - } + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + Set> violations = validator.validate(personRequest); + violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); } } diff --git a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java index 377d7e1..88b5da3 100644 --- a/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java +++ b/source-code/advanced/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java @@ -1,6 +1,7 @@ package com.example.beanvalidationdemo; import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; import com.example.beanvalidationdemo.service.PersonService; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,21 +17,20 @@ public class PersonServiceTest { @Autowired private PersonService service; - @Test(expected = ConstraintViolationException.class) - public void should_throw_exception_when_person_is_not_valid() { - Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); - service.validatePerson(person); + @Test + public void should_throw_exception_when_person_request_is_not_valid() { + try { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + service.validatePersonRequest(personRequest); + } catch (ConstraintViolationException e) { + e.getConstraintViolations().forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); + } } @Test(expected = ConstraintViolationException.class) public void should_check_person_with_groups() { Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); person.setGroup("group1"); service.validatePersonGroupForAdd(person); } @@ -38,9 +38,6 @@ public void should_check_person_with_groups() { @Test(expected = ConstraintViolationException.class) public void should_check_person_with_groups2() { Person person = new Person(); - person.setSex("Man22"); - person.setClassId("82938390"); - person.setEmail("SnailClimb"); service.validatePersonGroupForDelete(person); } diff --git a/source-code/start/hello-world/.gitignore b/source-code/bean-validation-demo/.gitignore similarity index 100% rename from source-code/start/hello-world/.gitignore rename to source-code/bean-validation-demo/.gitignore diff --git a/source-code/bean-validation-demo/.mvn/wrapper/MavenWrapperDownloader.java b/source-code/bean-validation-demo/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..7f91a56 --- /dev/null +++ b/source-code/bean-validation-demo/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/source-code/start/hello-world/.mvn/wrapper/maven-wrapper.jar b/source-code/bean-validation-demo/.mvn/wrapper/maven-wrapper.jar similarity index 100% rename from source-code/start/hello-world/.mvn/wrapper/maven-wrapper.jar rename to source-code/bean-validation-demo/.mvn/wrapper/maven-wrapper.jar diff --git a/source-code/start/hello-world/.mvn/wrapper/maven-wrapper.properties b/source-code/bean-validation-demo/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from source-code/start/hello-world/.mvn/wrapper/maven-wrapper.properties rename to source-code/bean-validation-demo/.mvn/wrapper/maven-wrapper.properties diff --git a/source-code/bean-validation-demo/mvnw b/source-code/bean-validation-demo/mvnw new file mode 100755 index 0000000..c188654 --- /dev/null +++ b/source-code/bean-validation-demo/mvnw @@ -0,0 +1,298 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/source-code/start/hello-world/mvnw.cmd b/source-code/bean-validation-demo/mvnw.cmd similarity index 100% rename from source-code/start/hello-world/mvnw.cmd rename to source-code/bean-validation-demo/mvnw.cmd diff --git a/source-code/bean-validation-demo/pom.xml b/source-code/bean-validation-demo/pom.xml new file mode 100644 index 0000000..c5a9e2f --- /dev/null +++ b/source-code/bean-validation-demo/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + com.example + bean-validation-demo + 0.0.1-SNAPSHOT + bean-validation-demo + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + org.projectlombok + lombok + true + + + junit + junit + 4.13.1 + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/BeanValidationDemoApplication.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/BeanValidationDemoApplication.java new file mode 100644 index 0000000..3f934bc --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/BeanValidationDemoApplication.java @@ -0,0 +1,13 @@ +package com.example.beanvalidationdemo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BeanValidationDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(BeanValidationDemoApplication.class, args); + } + +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/constants/Constants.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/constants/Constants.java new file mode 100644 index 0000000..8c20af3 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/constants/Constants.java @@ -0,0 +1,5 @@ +package com.example.beanvalidationdemo.constants; + +public final class Constants { + public static final String sexs = "((^Man$|^Woman$|^UGM$))"; +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/HelloWorldController.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/HelloWorldController.java new file mode 100644 index 0000000..8742cbf --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/HelloWorldController.java @@ -0,0 +1,19 @@ +package com.example.beanvalidationdemo.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author shuang.kou + * 验证基本环境搭建是否正确 + */ +@RestController +@RequestMapping("/api") +public class HelloWorldController { + + @GetMapping("/hello") + public String hello() { + return "Hello"; + } +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java new file mode 100644 index 0000000..c0482b5 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/controller/PersonController.java @@ -0,0 +1,38 @@ +package com.example.beanvalidationdemo.controller; + +import com.example.beanvalidationdemo.entity.PersonRequest; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.Valid; +import javax.validation.constraints.Max; +import javax.validation.constraints.Size; + +@RestController +@RequestMapping("/api/persons") +@Validated +public class PersonController { + + @PostMapping + public ResponseEntity save(@RequestBody @Valid PersonRequest personRequest) { + return ResponseEntity.ok().body(personRequest); + } + + @GetMapping("/{id}") + public ResponseEntity getPersonByID(@Valid @PathVariable("id") @Max(value = 5, message = "超过 id 的范围了") Integer id) { + return ResponseEntity.ok().body(id); + } + + @PutMapping + public ResponseEntity getPersonByName(@Valid @RequestParam("name") @Size(max = 6, message = "超过 name 的范围了") String name) { + return ResponseEntity.ok().body(name); + } +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java new file mode 100644 index 0000000..80bb5e8 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/Person.java @@ -0,0 +1,18 @@ +package com.example.beanvalidationdemo.entity; + +import com.example.beanvalidationdemo.service.AddPersonGroup; +import com.example.beanvalidationdemo.service.DeletePersonGroup; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Null; + +@Data +public class Person { + + // 当验证组为 DeletePersonGroup 的时候 group 字段不能为空 + @NotNull(groups = DeletePersonGroup.class) + // 当验证组为 AddPersonGroup 的时候 group 字段需要为空 + @Null(groups = AddPersonGroup.class) + private String group; +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java new file mode 100644 index 0000000..9b2c789 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/entity/PersonRequest.java @@ -0,0 +1,44 @@ +package com.example.beanvalidationdemo.entity; + +import com.example.beanvalidationdemo.validation.PhoneNumber; +import com.example.beanvalidationdemo.validation.Region; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/04/21 20:48 + **/ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class PersonRequest { + + @NotNull(message = "classId 不能为空") + private String classId; + + @Size(max = 33) + @NotNull(message = "name 不能为空") + private String name; + + @Pattern(regexp = "(^Man$|^Woman$|^UGM$)", message = "sex 值不在可选范围") + @NotNull(message = "sex 不能为空") + private String sex; + + @Region + private String region; + + @PhoneNumber(message = "phoneNumber 格式不正确") + @NotNull(message = "phoneNumber 不能为空") + private String phoneNumber; + +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/exception/GlobalExceptionHandler.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..c4f4e0a --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/exception/GlobalExceptionHandler.java @@ -0,0 +1,33 @@ +package com.example.beanvalidationdemo.exception; + +import com.example.beanvalidationdemo.controller.PersonController; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import javax.validation.ConstraintViolationException; +import java.util.HashMap; +import java.util.Map; + +@ControllerAdvice(assignableTypes = {PersonController.class}) +public class GlobalExceptionHandler { + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationExceptions( + MethodArgumentNotValidException ex) { + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); + } + + @ExceptionHandler(ConstraintViolationException.class) + ResponseEntity handleConstraintViolationException(ConstraintViolationException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); + } +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/AddPersonGroup.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/AddPersonGroup.java new file mode 100644 index 0000000..1f2950d --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/AddPersonGroup.java @@ -0,0 +1,4 @@ +package com.example.beanvalidationdemo.service; + +public interface AddPersonGroup { +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/DeletePersonGroup.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/DeletePersonGroup.java new file mode 100644 index 0000000..92f6713 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/DeletePersonGroup.java @@ -0,0 +1,4 @@ +package com.example.beanvalidationdemo.service; + +public interface DeletePersonGroup { +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java new file mode 100644 index 0000000..08e8e14 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/service/PersonService.java @@ -0,0 +1,28 @@ +package com.example.beanvalidationdemo.service; + +import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; +import org.springframework.stereotype.Service; +import org.springframework.validation.annotation.Validated; + +import javax.validation.Valid; + +@Service +@Validated +public class PersonService { + + public void validatePersonRequest(@Valid PersonRequest personRequest) { + // do something + } + + @Validated(AddPersonGroup.class) + public void validatePersonGroupForAdd(@Valid Person person) { + // do something + } + + @Validated(DeletePersonGroup.class) + public void validatePersonGroupForDelete(@Valid Person person) { + // do something + } + +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java new file mode 100644 index 0000000..afd5373 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumber.java @@ -0,0 +1,22 @@ +package com.example.beanvalidationdemo.validation; + +import javax.validation.Constraint; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented +@Constraint(validatedBy = PhoneNumberValidator.class) +@Target({FIELD, PARAMETER}) +@Retention(RUNTIME) +public @interface PhoneNumber { + String message() default "Invalid phone number"; + + Class[] groups() default {}; + + Class[] payload() default {}; +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java new file mode 100644 index 0000000..85acdcd --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/PhoneNumberValidator.java @@ -0,0 +1,21 @@ +package com.example.beanvalidationdemo.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class PhoneNumberValidator implements ConstraintValidator { + + @Override + public boolean isValid(String phoneField, ConstraintValidatorContext context) { + if (phoneField == null) { + // can be null + return true; + } + // 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 + // ^ 匹配输入字符串开始的位置 + // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d + // $ 匹配输入字符串结尾的位置 + String regExp = "^[1]((3[0-9])|(4[5-9])|(5[0-3,5-9])|([6][5,6])|(7[0-9])|(8[0-9])|(9[1,8,9]))\\d{8}$"; + return phoneField.matches(regExp); + } +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/Region.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/Region.java new file mode 100644 index 0000000..8b0a204 --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/Region.java @@ -0,0 +1,26 @@ +package com.example.beanvalidationdemo.validation; + +import javax.validation.Constraint; +import javax.validation.Payload; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * @author shuang.kou + */ +@Target({FIELD}) +@Retention(RUNTIME) +@Constraint(validatedBy = RegionValidator.class) +@Documented +public @interface Region { + + String message() default "Region 值不在可选范围内"; + + Class[] groups() default {}; + + Class[] payload() default {}; +} diff --git a/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/RegionValidator.java b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/RegionValidator.java new file mode 100644 index 0000000..9490c5b --- /dev/null +++ b/source-code/bean-validation-demo/src/main/java/com/example/beanvalidationdemo/validation/RegionValidator.java @@ -0,0 +1,17 @@ +package com.example.beanvalidationdemo.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import java.util.HashSet; + +public class RegionValidator implements ConstraintValidator { + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + HashSet regions = new HashSet<>(); + regions.add("China"); + regions.add("China-Taiwan"); + regions.add("China-HongKong"); + return regions.contains(value); + } +} diff --git a/source-code/bean-validation-demo/src/main/resources/application.properties b/source-code/bean-validation-demo/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java b/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java new file mode 100644 index 0000000..4f7e594 --- /dev/null +++ b/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonControllerTest.java @@ -0,0 +1,83 @@ +package com.example.beanvalidationdemo; + + +import com.example.beanvalidationdemo.entity.PersonRequest; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import java.util.Set; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +public class PersonControllerTest { + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + + /** + * 验证出现参数不合法的情况抛出异常并且可以正确被捕获 + */ + @Test + public void should_check_person_value() throws Exception { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390") + .region("Shanghai") + .phoneNumber("1816313815").build(); + mockMvc.perform(post("/api/persons") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(personRequest))) + .andExpect(MockMvcResultMatchers.jsonPath("sex").value("sex 值不在可选范围")) + .andExpect(MockMvcResultMatchers.jsonPath("name").value("name 不能为空")) + .andExpect(MockMvcResultMatchers.jsonPath("region").value("Region 值不在可选范围内")) + .andExpect(MockMvcResultMatchers.jsonPath("phoneNumber").value("phoneNumber 格式不正确")); + } + + @Test + public void should_check_path_variable() throws Exception { + mockMvc.perform(get("/api/persons/6") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("getPersonByID.id: 超过 id 的范围了")); + } + + @Test + public void should_check_request_param_value2() throws Exception { + mockMvc.perform(put("/api/persons") + .param("name", "snailclimbsnailclimb") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("getPersonByName.name: 超过 name 的范围了")); + } + + /** + * 手动校验对象 + */ + @Test + public void check_person_manually() { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + Set> violations = validator.validate(personRequest); + violations.forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); + } +} diff --git a/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java b/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java new file mode 100644 index 0000000..88b5da3 --- /dev/null +++ b/source-code/bean-validation-demo/src/test/java/com/example/beanvalidationdemo/PersonServiceTest.java @@ -0,0 +1,44 @@ +package com.example.beanvalidationdemo; + +import com.example.beanvalidationdemo.entity.Person; +import com.example.beanvalidationdemo.entity.PersonRequest; +import com.example.beanvalidationdemo.service.PersonService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.validation.ConstraintViolationException; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class PersonServiceTest { + @Autowired + private PersonService service; + + @Test + public void should_throw_exception_when_person_request_is_not_valid() { + try { + PersonRequest personRequest = PersonRequest.builder().sex("Man22") + .classId("82938390").build(); + service.validatePersonRequest(personRequest); + } catch (ConstraintViolationException e) { + e.getConstraintViolations().forEach(constraintViolation -> System.out.println(constraintViolation.getMessage())); + } + } + + @Test(expected = ConstraintViolationException.class) + public void should_check_person_with_groups() { + Person person = new Person(); + person.setGroup("group1"); + service.validatePersonGroupForAdd(person); + } + + @Test(expected = ConstraintViolationException.class) + public void should_check_person_with_groups2() { + Person person = new Person(); + service.validatePersonGroupForDelete(person); + } + +} diff --git a/source-code/hello-world/.gitignore b/source-code/hello-world/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/source-code/hello-world/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/source-code/start/hello-world/.mvn/wrapper/MavenWrapperDownloader.java b/source-code/hello-world/.mvn/wrapper/MavenWrapperDownloader.java similarity index 100% rename from source-code/start/hello-world/.mvn/wrapper/MavenWrapperDownloader.java rename to source-code/hello-world/.mvn/wrapper/MavenWrapperDownloader.java diff --git a/source-code/hello-world/.mvn/wrapper/maven-wrapper.jar b/source-code/hello-world/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/source-code/hello-world/.mvn/wrapper/maven-wrapper.jar differ diff --git a/source-code/hello-world/.mvn/wrapper/maven-wrapper.properties b/source-code/hello-world/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..cd0d451 --- /dev/null +++ b/source-code/hello-world/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/source-code/start/hello-world/mvnw b/source-code/hello-world/mvnw similarity index 100% rename from source-code/start/hello-world/mvnw rename to source-code/hello-world/mvnw diff --git a/source-code/hello-world/mvnw.cmd b/source-code/hello-world/mvnw.cmd new file mode 100644 index 0000000..fef5a8f --- /dev/null +++ b/source-code/hello-world/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/source-code/start/hello-world/pom.xml b/source-code/hello-world/pom.xml similarity index 100% rename from source-code/start/hello-world/pom.xml rename to source-code/hello-world/pom.xml diff --git a/source-code/start/hello-world/src/main/java/com/example/helloworld/HelloWorldApplication.java b/source-code/hello-world/src/main/java/com/example/helloworld/HelloWorldApplication.java similarity index 100% rename from source-code/start/hello-world/src/main/java/com/example/helloworld/HelloWorldApplication.java rename to source-code/hello-world/src/main/java/com/example/helloworld/HelloWorldApplication.java diff --git a/source-code/start/hello-world/src/main/java/com/example/helloworld/controller/UserController.java b/source-code/hello-world/src/main/java/com/example/helloworld/controller/UserController.java similarity index 100% rename from source-code/start/hello-world/src/main/java/com/example/helloworld/controller/UserController.java rename to source-code/hello-world/src/main/java/com/example/helloworld/controller/UserController.java diff --git a/source-code/start/hello-world/src/main/java/com/example/helloworld/dto/UserDto.java b/source-code/hello-world/src/main/java/com/example/helloworld/dto/UserDto.java similarity index 100% rename from source-code/start/hello-world/src/main/java/com/example/helloworld/dto/UserDto.java rename to source-code/hello-world/src/main/java/com/example/helloworld/dto/UserDto.java diff --git a/source-code/start/hello-world/src/main/java/com/example/helloworld/entity/User.java b/source-code/hello-world/src/main/java/com/example/helloworld/entity/User.java similarity index 100% rename from source-code/start/hello-world/src/main/java/com/example/helloworld/entity/User.java rename to source-code/hello-world/src/main/java/com/example/helloworld/entity/User.java diff --git a/source-code/start/hello-world/src/main/resources/application.properties b/source-code/hello-world/src/main/resources/application.properties similarity index 100% rename from source-code/start/hello-world/src/main/resources/application.properties rename to source-code/hello-world/src/main/resources/application.properties diff --git a/source-code/start/hello-world/src/test/java/com/example/dto2entity/BeanUtilsTest.java b/source-code/hello-world/src/test/java/com/example/dto2entity/BeanUtilsTest.java similarity index 100% rename from source-code/start/hello-world/src/test/java/com/example/dto2entity/BeanUtilsTest.java rename to source-code/hello-world/src/test/java/com/example/dto2entity/BeanUtilsTest.java diff --git a/source-code/start/hello-world/src/test/java/com/example/helloworld/HelloWorldApplicationTests.java b/source-code/hello-world/src/test/java/com/example/helloworld/HelloWorldApplicationTests.java similarity index 100% rename from source-code/start/hello-world/src/test/java/com/example/helloworld/HelloWorldApplicationTests.java rename to source-code/hello-world/src/test/java/com/example/helloworld/HelloWorldApplicationTests.java diff --git a/source-code/springboot-data-desensitization/.gitignore b/source-code/springboot-data-desensitization/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/source-code/springboot-data-desensitization/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/source-code/springboot-data-desensitization/.mvn/wrapper/MavenWrapperDownloader.java b/source-code/springboot-data-desensitization/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..a45eb6b --- /dev/null +++ b/source-code/springboot-data-desensitization/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.jar b/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.jar differ diff --git a/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.properties b/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffdc10e --- /dev/null +++ b/source-code/springboot-data-desensitization/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/source-code/springboot-data-desensitization/mvnw b/source-code/springboot-data-desensitization/mvnw new file mode 100755 index 0000000..3c8a553 --- /dev/null +++ b/source-code/springboot-data-desensitization/mvnw @@ -0,0 +1,322 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ]; then + + if [ -f /etc/mavenrc ]; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ]; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false +darwin=false +mingw=false +case "$(uname)" in +CYGWIN*) cygwin=true ;; +MINGW*) mingw=true ;; +Darwin*) + darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="$(/usr/libexec/java_home)" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ]; then + if [ -r /etc/gentoo-release ]; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +if [ -z "$M2_HOME" ]; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG="$(dirname "$PRG")/$link" + fi + done + + saveddir=$(pwd) + + M2_HOME=$(dirname "$PRG")/.. + + # make it fully qualified + M2_HOME=$(cd "$M2_HOME" && pwd) + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --unix "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw; then + [ -n "$M2_HOME" ] && + M2_HOME="$( ( + cd "$M2_HOME" + pwd + ))" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="$( ( + cd "$JAVA_HOME" + pwd + ))" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then + if $darwin; then + javaHome="$(dirname \"$javaExecutable\")" + javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" + else + javaExecutable="$(readlink -f \"$javaExecutable\")" + fi + javaHome="$(dirname \"$javaExecutable\")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ]; then + if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(which java)" + fi +fi + +if [ ! -x "$JAVACMD" ]; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ]; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ]; then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ]; do + if [ -d "$wdir"/.mvn ]; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$( + cd "$wdir/.." + pwd + ) + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' <"$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(pwd)") +if [ -z "$BASE_DIR" ]; then + exit 1 +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in wrapperUrl) + jarUrl="$value" + break + ;; + esac + done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl >/dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=$(cygpath --path --windows "$M2_HOME") + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/source-code/springboot-data-desensitization/mvnw.cmd b/source-code/springboot-data-desensitization/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/source-code/springboot-data-desensitization/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/source-code/springboot-data-desensitization/pom.xml b/source-code/springboot-data-desensitization/pom.xml new file mode 100644 index 0000000..baa65b9 --- /dev/null +++ b/source-code/springboot-data-desensitization/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + com.github.javaguide + springboot-data-desensitization + 0.0.1-SNAPSHOT + springboot-data-desensitization + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/SpringbootDataDesensitizationApplication.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/SpringbootDataDesensitizationApplication.java new file mode 100644 index 0000000..8fd6367 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/SpringbootDataDesensitizationApplication.java @@ -0,0 +1,13 @@ +package com.github.springbootdatadesensitization; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootDataDesensitizationApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootDataDesensitizationApplication.class, args); + } + +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializer.java new file mode 100644 index 0000000..8ea4523 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializer.java @@ -0,0 +1,59 @@ +package com.github.springbootdatadesensitization.desensitize; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.ContextualSerializer; +import com.github.springbootdatadesensitization.desensitize.annotation.JsonDesensitization; +import com.github.springbootdatadesensitization.desensitize.desensitizer.Desensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.DesensitizerFactory; +import com.github.springbootdatadesensitization.desensitize.enums.DesensitizationType; + +import java.io.IOException; +import java.util.Objects; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 20:26 + **/ +public class JsonDesensitizationSerializer extends JsonSerializer implements ContextualSerializer { + + + private DesensitizationType type; + + public JsonDesensitizationSerializer() { + } + + public JsonDesensitizationSerializer(DesensitizationType type) { + this.type = type; + } + + @Override + public JsonSerializer createContextual(SerializerProvider serializerProvider, BeanProperty property) throws JsonMappingException { + if (property != null) { + if (Objects.equals(property.getType().getRawClass(), String.class)) { + JsonDesensitization jsonDesensitization = property.getAnnotation(JsonDesensitization.class); + if (jsonDesensitization == null) { + jsonDesensitization = property.getContextAnnotation(JsonDesensitization.class); + } + if (jsonDesensitization != null) { + return new JsonDesensitizationSerializer(jsonDesensitization.value()); + } + } + return serializerProvider.findValueSerializer(property.getType(), property); + } else { + return serializerProvider.findNullValueSerializer(null); + } + } + + @Override + public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + Desensitizer desensitizer = DesensitizerFactory.get(this.type); + System.out.println(s); + jsonGenerator.writeString(desensitizer.desensitize(s)); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/annotation/JsonDesensitization.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/annotation/JsonDesensitization.java new file mode 100644 index 0000000..d7fbf5d --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/annotation/JsonDesensitization.java @@ -0,0 +1,25 @@ +package com.github.springbootdatadesensitization.desensitize.annotation; + +import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.github.springbootdatadesensitization.desensitize.JsonDesensitizationSerializer; +import com.github.springbootdatadesensitization.desensitize.enums.DesensitizationType; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 20:36 + **/ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD}) +@JacksonAnnotationsInside +@JsonSerialize(using = JsonDesensitizationSerializer.class) +public @interface JsonDesensitization { + DesensitizationType value(); +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/AbstractDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/AbstractDesensitizer.java new file mode 100644 index 0000000..32bbcd1 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/AbstractDesensitizer.java @@ -0,0 +1,71 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer; + +import com.github.springbootdatadesensitization.desensitize.exception.DesensitizationException; + +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * 数据脱敏所使用的的策略 + * + * @author Guide哥 + * @date 2021/05/10 20:15 + **/ +public abstract class AbstractDesensitizer implements Desensitizer { + + /** + * 左边的明文长度 + */ + private final Integer leftPlainTextLen; + /** + * 右边的明文长度 + */ + private Integer rightPlainTextLen; + + public AbstractDesensitizer(Integer leftPlainTextLen) { + this.leftPlainTextLen = leftPlainTextLen; + } + + public AbstractDesensitizer(Integer leftPlainTextLen, Integer rightPlainTextLen) { + this.leftPlainTextLen = leftPlainTextLen; + this.rightPlainTextLen = rightPlainTextLen; + } + + @Override + public String desensitize(String origin) { + if (origin == null || origin.isEmpty()) { + return ""; + } + // 处理邮箱的特殊情况 + if (isEmail(origin)) { + int index = origin.indexOf("@"); + rightPlainTextLen = origin.length() - index; + } + if (leftPlainTextLen == 0 && rightPlainTextLen == 0) { + return getEncryptedStr(6); + } + if (leftPlainTextLen < 0 || rightPlainTextLen < 0) { + throw new DesensitizationException("leftPlainTextLen and rightPlainTextLen must > 0"); + } + if (leftPlainTextLen + rightPlainTextLen >= origin.length()) { + throw new DesensitizationException("leftPlainTextLen+rightPlainTextLen should <= the length of origin"); + } + StringBuilder result = new StringBuilder(); + result.append(origin, 0, leftPlainTextLen); + result.append(getEncryptedStr(origin.length() - leftPlainTextLen - rightPlainTextLen)); + result.append(origin, origin.length() - rightPlainTextLen, origin.length()); + return result.toString(); + } + + private Boolean isEmail(String s) { + String emailRegex = "^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$"; + Pattern emailPattern = Pattern.compile(emailRegex); + return emailPattern.matcher(s).matches(); + } + + private String getEncryptedStr(int length) { + return Stream.generate(() -> "*").limit(length).collect(Collectors.joining()); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/Desensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/Desensitizer.java new file mode 100644 index 0000000..721009f --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/Desensitizer.java @@ -0,0 +1,11 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 20:36 + **/ +public interface Desensitizer { + String desensitize(String origin); +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/DesensitizerFactory.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/DesensitizerFactory.java new file mode 100644 index 0000000..f7d6fb3 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/DesensitizerFactory.java @@ -0,0 +1,45 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.AddressDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.BankCardDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.BirthdayDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.DefaultDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.EmailDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.IdCardDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.LandlineDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.MobileDesensitizer; +import com.github.springbootdatadesensitization.desensitize.desensitizer.impl.PasswordDesensitizer; +import com.github.springbootdatadesensitization.desensitize.enums.DesensitizationType; + +import java.util.HashMap; +import java.util.Map; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 23:18 + **/ +public class DesensitizerFactory { + public static final Map desensitizers = new HashMap<>(); + + static { + desensitizers.put(DesensitizationType.ADDRESS, new AddressDesensitizer()); + desensitizers.put(DesensitizationType.BANK_CARD, new BankCardDesensitizer()); + desensitizers.put(DesensitizationType.EMAIL, new EmailDesensitizer()); + desensitizers.put(DesensitizationType.ID_CARD, new IdCardDesensitizer()); + desensitizers.put(DesensitizationType.LANDLINE, new LandlineDesensitizer()); + desensitizers.put(DesensitizationType.MOBILE, new MobileDesensitizer()); + desensitizers.put(DesensitizationType.PASSWORD, new PasswordDesensitizer()); + desensitizers.put(DesensitizationType.DEFAULT, new DefaultDesensitizer()); + desensitizers.put(DesensitizationType.BIRTHDAY, new BirthdayDesensitizer()); + } + + public static Desensitizer get(DesensitizationType desensitizationType) { + Desensitizer desensitizer = desensitizers.get(desensitizationType); + if (desensitizer == null) { + return desensitizers.get(DesensitizationType.DEFAULT); + } + return desensitizer; + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/AddressDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/AddressDesensitizer.java new file mode 100644 index 0000000..cf9e429 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/AddressDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 地址脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:15 + **/ +public class AddressDesensitizer extends AbstractDesensitizer { + public AddressDesensitizer() { + super(3, 3); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BankCardDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BankCardDesensitizer.java new file mode 100644 index 0000000..b9620f9 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BankCardDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 银行卡号脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class BankCardDesensitizer extends AbstractDesensitizer { + public BankCardDesensitizer() { + super(3, 3); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BirthdayDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BirthdayDesensitizer.java new file mode 100644 index 0000000..1f8d300 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/BirthdayDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 密码脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class BirthdayDesensitizer extends AbstractDesensitizer { + public BirthdayDesensitizer() { + super(4, 0); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/DefaultDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/DefaultDesensitizer.java new file mode 100644 index 0000000..9a833de --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/DefaultDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 密码脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class DefaultDesensitizer extends AbstractDesensitizer { + public DefaultDesensitizer() { + super(0, 0); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/EmailDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/EmailDesensitizer.java new file mode 100644 index 0000000..3ea0fb4 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/EmailDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 邮箱脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class EmailDesensitizer extends AbstractDesensitizer { + public EmailDesensitizer() { + super(0); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/IdCardDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/IdCardDesensitizer.java new file mode 100644 index 0000000..d979913 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/IdCardDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 身份证号脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class IdCardDesensitizer extends AbstractDesensitizer { + public IdCardDesensitizer() { + super(3, 4); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/LandlineDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/LandlineDesensitizer.java new file mode 100644 index 0000000..5bec86e --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/LandlineDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 座机号脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class LandlineDesensitizer extends AbstractDesensitizer { + public LandlineDesensitizer() { + super(2, 2); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/MobileDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/MobileDesensitizer.java new file mode 100644 index 0000000..2482a9c --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/MobileDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 手机号脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class MobileDesensitizer extends AbstractDesensitizer { + public MobileDesensitizer() { + super(3, 4); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/PasswordDesensitizer.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/PasswordDesensitizer.java new file mode 100644 index 0000000..62639ff --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/desensitizer/impl/PasswordDesensitizer.java @@ -0,0 +1,15 @@ +package com.github.springbootdatadesensitization.desensitize.desensitizer.impl; + +import com.github.springbootdatadesensitization.desensitize.desensitizer.AbstractDesensitizer; + +/** + * 密码脱敏 + * + * @author Guide哥 + * @date 2021/05/10 20:28 + **/ +public class PasswordDesensitizer extends AbstractDesensitizer { + public PasswordDesensitizer() { + super(0, 0); + } +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/enums/DesensitizationType.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/enums/DesensitizationType.java new file mode 100644 index 0000000..502cf70 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/enums/DesensitizationType.java @@ -0,0 +1,46 @@ +package com.github.springbootdatadesensitization.desensitize.enums; + +/** + * 微信搜 JavaGuide 回复"面试突击"即可免费领取个人原创的 Java 面试手册 + * + * @author Guide哥 + * @date 2021/05/10 20:36 + **/ +public enum DesensitizationType { + + DEFAULT, + /** + * 座机号 + */ + LANDLINE, + /** + * 手机 + */ + MOBILE, + /** + * 邮箱 + */ + EMAIL, + + /** + * 生日🎂 + */ + BIRTHDAY, + /** + * 密码 + */ + PASSWORD, + /** + * 身份证 + */ + ID_CARD, + /** + * 银行卡 + */ + BANK_CARD, + /** + * 地址 + */ + ADDRESS, + +} diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/exception/DesensitizationException.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/exception/DesensitizationException.java new file mode 100644 index 0000000..50a70b4 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/desensitize/exception/DesensitizationException.java @@ -0,0 +1,14 @@ +package com.github.springbootdatadesensitization.desensitize.exception; + +import lombok.Getter; + +/** + * @author shuang.kou + * @date 2017/12/19 14:25 + */ +@Getter +public class DesensitizationException extends RuntimeException { + public DesensitizationException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/entity/User.java b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/entity/User.java new file mode 100644 index 0000000..6dcbda5 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/java/com/github/springbootdatadesensitization/entity/User.java @@ -0,0 +1,35 @@ +package com.github.springbootdatadesensitization.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.github.springbootdatadesensitization.desensitize.annotation.JsonDesensitization; +import com.github.springbootdatadesensitization.desensitize.enums.DesensitizationType; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class User { + private Long id; + @JsonDesensitization(DesensitizationType.EMAIL) + private String email; + + @JsonDesensitization(DesensitizationType.ID_CARD) + private String idCard; + + @JsonDesensitization(DesensitizationType.PASSWORD) + private String password; + + @JsonDesensitization(DesensitizationType.MOBILE) + private String phone; + + @JsonFormat(pattern = "yyyy-MM-dd", locale = "zh", timezone = "GMT+8") + @JsonDesensitization(DesensitizationType.BIRTHDAY) + private Date birthday; +} diff --git a/source-code/springboot-data-desensitization/src/main/resources/application.properties b/source-code/springboot-data-desensitization/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/source-code/springboot-data-desensitization/src/test/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializerTest.java b/source-code/springboot-data-desensitization/src/test/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializerTest.java new file mode 100644 index 0000000..3debd98 --- /dev/null +++ b/source-code/springboot-data-desensitization/src/test/java/com/github/springbootdatadesensitization/desensitize/JsonDesensitizationSerializerTest.java @@ -0,0 +1,33 @@ +package com.github.springbootdatadesensitization.desensitize; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.springbootdatadesensitization.entity.User; +import org.junit.jupiter.api.Test; + +import java.util.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class JsonDesensitizationSerializerTest { + + @Test + void should_desensitize_entity() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + User user = User.builder() + .birthday(new Date()) + .phone("1816313814") + .email("136148@qq.com") + .password("12dsfs@dfsdg431") + .idCard("463827319960397495") + .build(); + String s = objectMapper.writeValueAsString(user); + System.out.println(s); + User desensitizedUser = objectMapper.readValue(s, User.class); + assertEquals("******@qq.com", desensitizedUser.getEmail()); + assertEquals("463***********7495", desensitizedUser.getIdCard()); + assertEquals("******", desensitizedUser.getPassword()); + assertEquals("181***3814", desensitizedUser.getPhone()); + + } +} \ No newline at end of file diff --git a/springboot-schedule-task/.idea/workspace.xml b/springboot-schedule-task/.idea/workspace.xml deleted file mode 100644 index 7120d02..0000000 --- a/springboot-schedule-task/.idea/workspace.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1573625912874 - - - - - - - - - \ No newline at end of file