diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index e848d82..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.github/.DS_Store b/.github/.DS_Store deleted file mode 100644 index c29fa0a..0000000 Binary files a/.github/.DS_Store and /dev/null differ diff --git a/README.md b/README.md index 68e0616..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,9 +19,13 @@ 公众号 公众号

- **在线阅读** : https://snailclimb.gitee.io/springboot-guide (上面的地址访问速度缓慢的建议使用这个路径访问) +**开源的目的是为了大家能一起完善,如果你觉得内容有任何需要完善/补充的地方,欢迎提交 issue/pr。** + +- Github地址:https://github.com/CodingDocs/springboot-guide +- 码云地址:https://gitee.com/SnailClimb/springboot-guide(Github无法访问或者访问速度比较慢的小伙伴可以看码云上的对应内容) + ## 重要知识点 ### 基础 @@ -25,17 +38,19 @@ 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. [SpringBoot 2.0+ 集成 Swagger 官方 Starter + knife4j 增强方案](./docs/basis/swagger.md) +9. [MyBatis-Plus 从入门到上手干事!](./docs/MyBatisPlus.md) +10. [SpringBoot 2.0+ 集成 Swagger 官方 Starter + knife4j 增强方案](./docs/basis/swagger.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/advanced/spring-bean-validation.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) ### 补充 @@ -53,11 +68,9 @@ 1. 项目 logo 由 [logoly](https://logoly.pro/#/) 生成。 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) ### 公众号 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/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/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 5a8d16d..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 | +- 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,9 +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](https://github.com/Snailclimb/springboot-guide/tree/master/source-code/start/hello-world)(建议自己手敲一遍!!!) +## 总结 +通过本文我们学到了如何新建 Spring Boot 项目、SpringBoot 项目常见的项目结构分析、`@SpringBootApplication` 注解分析,最后实现了 Spring Boot 版的 "Hello World"。 \ 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/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