「记录」Spring经验总结
# @Validated
# 常用注解
注释 | 说明 |
---|---|
@Null | x == null |
@NotNull | x != null |
@AssertFalse | x == false |
@AssertTrue | x == true |
@DecimalMax(value) | x <= "value" |
@DecimalMin(value) | x >= "value" |
@Digits(integer,fraction) | 限制数字位数范围,integer 表示数字的整数位数,fraction 表示数字的小数位数 |
@Max(value) | x <= value |
@Min(value) | x >= value |
@Size(max,min) | x <= max && x >= min |
@Positive | x > 0 |
@Future | 限制必须是一个将来的日期 |
@Past | 限制必须是一个过去的日期 |
@Pattern(value) | 限制必须符合指定的正则表达式 |
@NotEmpty | 验证注解的元素值不为 null 且不为空(字符串长度不为 0、集合大小不为 0) |
@NotBlank | 验证注解的元素值不为空(不为 null、去除首位空格后长度为 0),不同于 @NotEmpty,@NotBlank 只应用于字符串且在比较时会去除字符串的空格 |
验证注解的元素值是 Email,也可以通过正则表达式和 flag 指定自定义的 email 格式 | |
@Valid | 校验集合中的对象属性的校验注解 |
# @Valid 校验 List 中的对象属性的校验注解
class Student{
@Valid
private List<Course> courseList;
}
# Controller 方法入参基本类型校验
@Validated
public class TestController {
@PostMapping("/cancel/{id}")
public DataResponse<Void> cancel(@NotNull(message = "id不能为空") @PathVariable(value = "id") Long id) {
return DataResponse.ok();
}
}
如方法入参是一个基本类型包装对象,需非空校验,应在类上添加 @Validated
注解,并在校验对象前添加 @NotNull
注解
参考资料
# @Component
# 默认 bean 名称
注解的 value
没有赋值时,将根据类名转小驼峰生成 bean 名称,除非前两个字母是大写的。例如:
com.xyz.FooServiceImpl -> fooServiceImpl
com.xyz.URLFooServiceImpl -> URLFooServiceImpl
参考资料
# @Cacheable 缓存
用于将某类或某方法缓存
cacheNames/value
:用来指定缓存组件的名字key
:缓存数据时使用的 key,可以用它来指定。默认是使用方法参数的值。(这个 key 你可以使用 spEL 表达式来编写)keyGenerator
:key 的生成器。 key 和 keyGenerator 二选一使用cacheManager
:可以用来指定缓存管理器。从哪个缓存管理器里面获取缓存。condition
:可以用来指定符合条件的情况下才缓存unless
:否定缓存。当 unless 指定的条件为 true ,方法的返回值就不会被缓存。当然你也可以获取到结果进行判断。(通过#result
获取方法结果)sync
:是否使用异步模式。
参考资料
- SpringBoot 缓存之 @Cacheable 详细介绍_zl1zl2zl3 的博客 - CSDN 博客[email protected] (opens new window)
- @cacheable 设置过期时间_Spring cache 整合 Redis,并给它一个过期时间!_为了看看的博客 - CSDN 博客 (opens new window)
# @CacheEvict 删除缓存
# @ConfigurationProperties 配置注入
# Spring Boot <2.2
定义配置文件映射对象:
@Configuration
@ConfigurationProperties(prefix="myconfig")
@Data
public class MyProperties{
private String username;
private String password;
}
两种注入方式
- 在 Properties 类上添加
@Configuration
注解 - 在启动类添加
@EnableConfigurationProperties(MyProperties.class)
注解
# Spring Boot >=2.2
@ConfigurationProperties(prefix = "mail")
@ConfigurationPropertiesScan
@Data
public class ConfigProperties {
private String hostName;
private int port;
private String from;
}
两种注入方式
- 在 Properties 类上添加
@ConfigurationPropertiesScan
注解(代替@Configuration
注解) - 在启动类添加
@ConfigurationPropertiesScan("com.baeldung.configurationproperties")
注解
# 总结
Spring Boot >=2.2 的新特性 @ConfigurationPropertiesScan
最佳实践应使用在启动类上,只需指定包路径,之后只需按照约定的包路径配置即可以自动注入。
参考:Guide to @ConfigurationProperties in Spring Boot (opens new window)
上次更新: 2023/06/10, 18:45:20