Spring的Assert工具类的用法
简介
今天在看spring mvc源码时看到下面代码,感觉蛮有意思的,在这里记录下
Assert断言工具类,通常用于数据合法性检查,在JAVA编程中,通常会编写如下代码:
if (name == null || name.equls("")) {
throw new IllegalArgumentException("参数错误!");
}
在所有方法中都使用手工检测合法性的方式并不是太好,因为这样影响了代码的可读性,若使用Assert工具类上面的代码可以简化为:
Assert.hasText((name, "参数错误!");
这样可以大大增强代码的可读性,下面我们来介绍一下Assert 类中的常用断言方法:
notNull(Object object, "object is required") - 对象非空 3hf
isTrue(Object object, "object must be true") - 对象必须为true
notEmpty(Collection collection, "collection must not be empty") - 集合非空
hasLength(String text, "text must be specified") - 字符不为null且字符长度不为0
hasText(String text, "text must not be empty") - text 不为null且必须至少包含一个非空格的字符
isInstanceOf(Class clazz, Object obj, "clazz must be of type [clazz]") - obj必须能被正确造型成为clazz 指定的类
相关文章
- spring中context:property-placeholder/元素
- SpringBoot之整合Redis分析和实现-基于Spring Boot2.0.2版本
- spring cloud: Hystrix(三):健康指数 health Indicator
- spring: 在Spring应用中使用JDBC(使用profiles选择数据源/使用基于JDBC驱动的数据源)
- Spring Boot 微服务性能下降九成!使用 Arthas 定位根因
- 01-spring安装,hello word
- Sentinel Getting Started And Integration of Spring Cloud Alibaba Tutorials
- [Spring学习笔记 3 ] spring 注解详解,完全注解,常用注解
- [React Native] Animate the Scale of a React Native Button using Animated.spring
- spring boot:使用mybatis访问多个mysql数据源/查看Hikari连接池的统计信息(spring boot 2.3.1)
- spring 学习3-Spring AOP
- [Spring学习笔记 3 ] spring 注解详解,完全注解,常用注解
- Spring事务管理
- Spring Data ElasticSearch示例--查询索引库
- 【工具类】手动获取被spring管理的bean对象
- Spring实战3:装配bean的进阶知识
- Atitit spring单元测试 注解 获取服务名 Spring文件单独放在一个文件夹,去掉dubbo配置,方便测试 里面包含的mybatis 找不到,只好设置成相对于class绝对路径可以了
- 基于CSE的微服务架构实践-Spring Boot技术栈选型
- 学习Spring Boot:(十四)spring-shiro的密码加密
- spring boot配置tomcat部署
- 从头认识Spring-1.14 SpEl表达式(1)-简单介绍与嵌入值
- 毕业设计 Spring Boot个人健康信息管理系统(含源码+论文)
- Spring JDBC SimpleJdbcCall类示例
- spring事务报错Error occured processing XML org/springframework/aop/config/AopNamespaceUtils,See Error