1. 注解目录

2. Spring bean相关
2.1 @Autowired
自动导入对象到类中(自动装配),被注入的类同样要被 Spring 容器管理,比如:Service 类注入到 Controller 类中。
2.2 @Component, @Repository, @Service, @Controller
我们一般使用 @Autowired 注解让 Spring 容器帮我们自动装配 bean。要想把类标识成可用于 @Autowired 注解自动装配的 bean 的类,可以采用以下注解实现:
@Component:通用的注解,可标注任意类为Spring组件。如果一个 Bean 不知道属于哪个层,可以使用@Component注解标注;@Repository: 对应持久层即 Dao 层,主要用于数据库相关操作;@Service: 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao 层;@Controller: 对应 Spring MVC 控制层,主要用于接受用户请求并调用 Service 层返回数据给前端页面。2.3
@RestController@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器 bean,并且是将函数的返回值直接填入 HTTP 响应体中,是 REST 风格的控制器。@Controller+@ResponseBody返回 JSON 或 XML 形式数据2.4
**@Scope**声明 Spring Bean 的作用域。
@Bean@Scope("singleton")public Person personSingleton() {return new Person();}
四种常见的 Spring Bean 的作用域:
singleton : 唯一 bean 实例,Spring 中的 bean 默认都是单例的;
- prototype : 每次请求都会创建一个新的 bean 实例;
- request : 每一次 HTTP 请求都会产生一个新的 bean,该 bean 仅在当前 HTTP request 内有效;
- session : 每一次 HTTP 请求都会产生一个新的 bean,该 bean 仅在当前 HTTP session 内有效。
2.5
一般用来声明配置类,可以使用@Configuration@Component注解替代,不过使用Configuration注解声明配置类更加语义化。@Configurationpublic class AppConfig {@Beanpublic TransferService transferService() {return new TransferServiceImpl();}}
2.6
Spring 的 @Bean 注解用于告诉方法,产生一个 Bean 对象,然后这个 Bean 对象交给 Spring 管理,和 xml 配置中的 bean 标签的作用是一样的。@Bean@Component和@Bean的区别?@Component:表明一个类会作为组件类,并告知 Spring 要为这个类创建 bean。@Bean:一般用在配置类中的方法上,告诉 Spring 这个方法将会返回一个对象,这个对象要注册为 Spring 应用上下文中的 bean。通常方法体中包含了最终产生 bean 实例的逻辑。- 两者的目的是一样的,都是注册 bean 到 Spring 容器中,两者都可以通过
@Autowired进行装配。但是@Bean比@Component的自定义性更强。可以实现一些@Component实现不了的自定义加载类(比如我们将第三方组件装配到应用中,是没法用@Component注解的,可以使用@Bean)。
3. 常见的http请求(Get、Post…)
@GetMapping("users"):等价于@RequestMapping(value="/users",method=RequestMethod.GET)。@PostMapping("users"):等价于@RequestMapping(value="/users",method=RequestMethod.POST)。@PutMapping("/users/{userId}"):等价于@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT)。@DeleteMapping("/users/{userId}"):等价于@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE)。
4. 前后端传值
4.1 @PathVariable和@RequestParam
@PathVariable:将请求 URL中占位符参数 {xxx} 绑定到控制器的方法参数上。@RequestParam:将请求参数绑定到你控制器的方法参数上,required = true 表示该请求路径中必须包含该参数,如果不包含就报错。
举个简单的例子:
@RestControllerpublic class TestController {@GetMapping("/api/{id}/add")public String testPathVariableAndRequestParam(@PathVariable("id") Long id,@RequestParam(value = "type", required = false) String type) {if (id == 1) {return "ok" + ",id=" + id + ",type=" + type;}return "fail" + ",id=" + id + ",type=" + type;}}
4.2 @RequestBody
@RequestBody:用于读取 Request 请求的 body 部分并且 Content-Type 为 application/json 格式的数据,接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用HttpMessageConverter或者自定义的HttpMessageConverter将请求的 body 中的 json 字符串转换为 java 对象。
举个简单的例子:
@PostMapping("/api/add")public String testResponseBody(@RequestBody Student student) {return student.toString();}
post 请求结果如下:
注解:一个请求方法只可以有一个
@RequestBody,但是可以有多个@RequestParam和@PathVariable。 如果你的方法必须要用两个@RequestBody来接受数据的话,大概率是你的数据库设计或者系统设计出问题了!
5. 读取配置信息
5.1 @Value
很多时候我们需要将一些常用的配置信息比如阿里云 oss、发送短信、微信认证的相关配置信息等等放到配置文件 application.yml 中,并且我们会在 Java 代码中读取一些配置信息。配置文件如下:
wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!my-profile:name: Guide哥email: koushuangbwcx@163.comlibrary:location: 湖北武汉加油中国加油books:- name: 天才基本法description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。- name: 时间的秩序description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。- name: 了不起的我description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻?
使用 @Value("${property}") 读取比较简单的配置信息:
@Value("${wuhan2020}")String wuhan2020;
5.2 @ConfigurationProperties(常用)
通过@ConfigurationProperties读取配置信息并与 bean 绑定,你可以像使用普通的 Spring bean 一样,将其注入到类中使用。
@Component@ConfigurationProperties(prefix = "library")class LibraryProperties {@NotEmptyprivate String location;private List<Book> books;@Setter@Getter@ToStringstatic class Book {String name;String description;}省略getter/setter......}
5.3 @PropertySource(不常用)
@PropertySource读取指定 properties 文件
@Component@PropertySource("classpath:website.properties")class WebSite {@Value("${url}")private String url;省略getter/setter......}
6. 参数校验
数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。
JSR(Java Specification Requests) 是一套 JavaBean 参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们 JavaBean 的属性上面,这样就可以在需要校验的时候进行校验了,非常方便!
校验的时候我们实际用的是 Hibernate Validator 框架。
SpringBoot 项目的 spring-boot-starter-web 依赖中已经有 hibernate-validator 包,不需要引用相关依赖。如下图所示(通过 idea 插件—Maven Helper 生成):
需要注意的是: 所有的注解,推荐使用 JSR 注解,即**javax.validation.constraints**,而不是**org.hibernate.validator.constraints**
6.1. 一些常用的字段验证的注解
@NotEmpty被注释的字符串的不能为 null 也不能为空@NotBlank被注释的字符串非 null,并且必须包含一个非空白字符@Null被注释的元素必须为 null@NotNull被注释的元素必须不为 null@AssertTrue被注释的元素必须为 true@AssertFalse被注释的元素必须为 false@Pattern(regex=,flag=)被注释的元素必须符合指定的正则表达式@Email被注释的元素必须是 Email 格式@Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@DecimalMin(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@DecimalMax(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@Size(max=, min=)被注释的元素的大小必须在指定的范围内@Digits (integer, fraction)被注释的元素必须是一个数字,其值必须在可接受的范围内@Past被注释的元素必须是一个过去的日期@Future被注释的元素必须是一个将来的日期6.2. 验证请求体(RequestBody)
我们在需要验证的参数上加上了@Data@AllArgsConstructor@NoArgsConstructor@Validatedpublic 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;}
@Valid注解,如果验证失败,它将抛出MethodArgumentNotValidException。@RestController@RequestMapping("/api")@Validatedpublic class PersonController {@PostMapping("/person")public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) {return ResponseEntity.ok().body(person);}}
6.3. 验证请求参数(Path Variables 和 Request Parameters)
一定一定不要忘记在类上加上@Validated注解了,这个注解可以告诉 Spring 去校验方法参数。@RestController@RequestMapping("/api")@Validatedpublic class PersonController {@GetMapping("/person/{id}")public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) {return ResponseEntity.ok().body(id);}}
7. 全局异常处理
介绍一下我们 Spring 项目必备的全局处理 Controller 层异常。
相关注解:
@ControllerAdvice:它是一个 Controller 增强器,可对 controller 中被 @RequestMapping 注解的方法加一些逻辑处理,最常用的就是异常处理。@ExceptionHandler:注解声明异常处理方法。
如何使用呢?拿我们在参数校验这块来举例子。如果方法参数不对的话就会抛出MethodArgumentNotValidException,我们来处理这个异常。
@ControllerAdvice@ResponseBodypublic class GlobalExceptionHandler {/*** 请求参数异常处理*/@ExceptionHandler(MethodArgumentNotValidException.class)public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {......}}
8. JPA 相关
8.1. 创建表
@Entity声明一个类对应一个数据库实体。@Table 设置表明
@Entity@Table(name = "role")public class Role {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;private String description;省略getter/setter......}
8.2. 创建主键
@Id :声明一个字段为主键。
使用@Id声明之后,我们还需要定义主键的生成策略。我们可以使用 @GeneratedValue 指定主键生成策略。
1.通过 **@GeneratedValue**直接使用 JPA 内置提供的四种主键生成策略来指定主键生成策略。
@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;
JPA 使用枚举定义了 4 中常见的主键生成策略,如下:
枚举替代常量的一种用法
public enum GenerationType {/*** 使用一个特定的数据库表格来保存主键* 持久化引擎通过关系数据库的一张特定的表格来生成主键,*/TABLE,/***在某些数据库中,不支持主键自增长,比如Oracle、PostgreSQL其提供了一种叫做"序列(sequence)"的机制生成主键*/SEQUENCE,/*** 主键自增长*/IDENTITY,/***把主键生成策略交给持久化引擎(persistence engine),*持久化引擎会根据数据库在以上三种主键生成 策略中选择其中一种*/AUTO}
@GeneratedValue注解默认使用的策略是GenerationType.AUTO
public @interface GeneratedValue {GenerationType strategy() default AUTO;String generator() default "";}
一般使用 MySQL 数据库的话,使用GenerationType.IDENTITY策略比较普遍一点(分布式系统的话需要另外考虑使用分布式 ID)。
2.通过 **@GenericGenerator**声明一个主键策略,然后 **@GeneratedValue**使用这个策略
@Id@GeneratedValue(generator = "IdentityIdGenerator")@GenericGenerator(name = "IdentityIdGenerator", strategy = "identity")private Long id;
等价于:
@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;
jpa 提供的主键生成策略有如下几种:
public class DefaultIdentifierGeneratorFactoryimplements MutableIdentifierGeneratorFactory, Serializable, ServiceRegistryAwareService {@SuppressWarnings("deprecation")public DefaultIdentifierGeneratorFactory() {register( "uuid2", UUIDGenerator.class );register( "guid", GUIDGenerator.class ); // can be done with UUIDGenerator + strategyregister( "uuid", UUIDHexGenerator.class ); // "deprecated" for new useregister( "uuid.hex", UUIDHexGenerator.class ); // uuid.hex is deprecatedregister( "assigned", Assigned.class );register( "identity", IdentityGenerator.class );register( "select", SelectGenerator.class );register( "sequence", SequenceStyleGenerator.class );register( "seqhilo", SequenceHiLoGenerator.class );register( "increment", IncrementGenerator.class );register( "foreign", ForeignGenerator.class );register( "sequence-identity", SequenceIdentityGenerator.class );register( "enhanced-sequence", SequenceStyleGenerator.class );register( "enhanced-table", TableGenerator.class );}public void register(String strategy, Class generatorClass) {LOG.debugf( "Registering IdentifierGenerator strategy [%s] -> [%s]", strategy, generatorClass.getName() );final Class previous = generatorStrategyToClassNameMap.put( strategy, generatorClass );if ( previous != null ) {LOG.debugf( " - overriding [%s]", previous.getName() );}}}
8.3. 设置字段类型
@Column 声明字段。
示例:
设置属性 userName 对应的数据库字段名为 user_name,长度为 32,非空
@Column(name = "user_name", nullable = false, length=32)private String userName;
设置字段类型并且加默认值,这个还是挺常用的。
Column(columnDefinition = "tinyint(1) default 1")private Boolean enabled;
8.4. 指定不持久化特定字段
@Transient :声明不需要与数据库映射的字段,在保存的时候不需要保存进数据库 。
如果我们想让secrect 这个字段不被持久化,可以使用 @Transient关键字声明。
Entity(name="USER")public class User {......@Transientprivate String secrect; // not persistent because of @Transient}
除了 @Transient关键字声明, 还可以采用下面几种方法:
static String secrect; // not persistent because of staticfinal String secrect = “Satish”; // not persistent because of finaltransient String secrect; // not persistent because of transient
8.5. 声明大字段
@Lob:声明某个字段为大字段。
@Lobprivate String content;
更详细的声明:
@Lob//指定 Lob 类型数据的获取策略, FetchType.EAGER 表示非延迟 加载,而 FetchType. LAZY 表示延迟加载 ;@Basic(fetch = FetchType.EAGER)//columnDefinition 属性指定数据表对应的 Lob 字段类型@Column(name = "content", columnDefinition = "LONGTEXT NOT NULL")private String content;
8.6. 创建枚举类型的字段
可以使用枚举类型的字段,不过枚举字段要用@Enumerated注解修饰。
public enum Gender {MALE("男性"),FEMALE("女性");private String value;Gender(String str){value=str;}}@Entity@Table(name = "role")public class Role {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;private String description;@Enumerated(EnumType.STRING)private Gender gender;省略getter/setter......}
8.7. 增加审计功能
只要继承了 AbstractAuditBase的类都会默认加上下面四个字段。
@Data@AllArgsConstructor@NoArgsConstructor@MappedSuperclass@EntityListeners(value = AuditingEntityListener.class)public abstract class AbstractAuditBase {@CreatedDate@Column(updatable = false)@JsonIgnoreprivate Instant createdAt;@LastModifiedDate@JsonIgnoreprivate Instant updatedAt;@CreatedBy@Column(updatable = false)@JsonIgnoreprivate String createdBy;@LastModifiedBy@JsonIgnoreprivate String updatedBy;}
我们对应的审计功能对应地配置类可能是下面这样的(Spring Security 项目):
@Configuration@EnableJpaAuditingpublic class AuditSecurityConfiguration {@BeanAuditorAware<String> auditorAware() {return () -> Optional.ofNullable(SecurityContextHolder.getContext()).map(SecurityContext::getAuthentication).filter(Authentication::isAuthenticated).map(Authentication::getName);}}
简单介绍一下上面设计到的一些注解:
@CreatedDate: 表示该字段为创建时间时间字段,在这个实体被 insert 的时候,会设置值@CreatedBy:表示该字段为创建人,在这个实体被 insert 的时候,会设置值@LastModifiedDate、@LastModifiedBy同理。
@EnableJpaAuditing:开启 JPA 审计功能。
8.8. 删除/修改数据
@Modifying 注解提示 JPA 该操作是修改操作,注意还要配合@Transactional注解使用。
@Repositorypublic interface UserRepository extends JpaRepository<User, Integer> {@Modifying@Transactional(rollbackFor = Exception.class)void deleteByUserName(String userName);}
8.9. 关联关系
@OneToOne声明一对一关系@OneToMany声明一对多关系@ManyToOne声明多对一关系MangToMang声明多对多关系
9. 事务@Transactional
在要开启事务的方法上使用@Transactional注解即可!
@Transactional(rollbackFor = Exception.class)public void save() {......}
我们知道 Exception 分为运行时异常 RuntimeException 和非运行时异常。在@Transactional注解中如果不配置rollbackFor属性,那么事物只会在遇到RuntimeException的时候才会回滚,加上rollbackFor=Exception.class,可以让事物在遇到非运行时异常时也回滚。@Transactional 注解一般用在可以作用在类或者方法上。
- 作用于类:当把
@Transactional 注解放在类上时,表示所有该类的public 方法都配置相同的事务属性信息。 - 作用于方法:当类配置了
@Transactional,方法也配置了@Transactional,方法的事务会覆盖类的事务配置信息。
10 Json数据处理
10.1. 过滤json数据
@JsonIgnoreProperties 作用在类上用于过滤掉特定字段不返回或者不解析。
//生成json时将userRoles属性过滤@JsonIgnoreProperties({"userRoles"})public class User {private String userName;private String fullName;private String password;@JsonIgnoreprivate List<UserRole> userRoles = new ArrayList<>();}
@JsonIgnore一般用于类的属性上,作用和上面的@JsonIgnoreProperties 一样。
public class User {private String userName;private String fullName;private String password;//生成json时将userRoles属性过滤@JsonIgnoreprivate List<UserRole> userRoles = new ArrayList<>();}
10.2 格式化json数据
@JsonFormat一般用来格式化 json 数据。:
比如:
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")private Date date;
10.3 扁平化对象
@Getter@Setter@ToStringpublic class Account {@JsonUnwrappedprivate Location location;@JsonUnwrappedprivate PersonInfo personInfo;@Getter@Setter@ToStringpublic static class Location {private String provinceName;private String countyName;}@Getter@Setter@ToStringpublic static class PersonInfo {private String userName;private String fullName;}}
未扁平化之前:
{"location": {"provinceName":"湖北","countyName":"武汉"},"personInfo": {"userName": "coder1234","fullName": "shaungkou"}}
使用@JsonUnwrapped 扁平对象之后:
@Getter@Setter@ToStringpublic class Account {@JsonUnwrappedprivate Location location;@JsonUnwrappedprivate PersonInfo personInfo;......}{"provinceName":"湖北","countyName":"武汉","userName": "coder1234","fullName": "shaungkou"}
11. 测试相关
@ActiveProfiles一般作用于测试类上, 用于声明生效的 Spring 配置文件。
@SpringBootTest(webEnvironment = RANDOM_PORT)@ActiveProfiles("test")@Slf4jpublic abstract class TestBase {......}
@Test声明一个方法为测试方法@Transactional被声明的测试方法的数据会回滚,避免污染测试数据。@WithMockUser Spring Security 提供的,用来模拟一个真实用户,并且可以赋予权限。
@Test@Transactional@WithMockUser(username = "user-id-18163138155", authorities = "ROLE_TEACHER")void should_import_student_success() throws Exception {......}
12. 高级特性
12.1 @Schedule
@Schedule 注解是 Spring 实现定时任务的一种方式,相比 Java 起周期性线程池实现定时任务,这种纯注解的方式更简洁。
12.1.1 使用方法
- 在springboot启动类加上注解:
**@EnableScheduling**; - 新建一个定时任务类,需要添加
**@Component**或者**@Service**注解; - 在任务类中添加具体的定时任务方法,方法上用
**@Schedule**注解修饰,注解里有两个重要参数:- fixedRate:指定两次任务执行的时间间隔(毫秒),前一个任务开始与下一个任务开始的间隔,需要注意:如果任务执行的时间大于间隔,会导致阻塞,因为@Schedule默认是单线程的;
- fixedDelay:指定两次任务执行的时间间隔(毫秒),前一个任务结束与下一个任务开始的间隔。
- 一个定时任务类中可以有多个定时任务方法,一个项目里必然可以有多个定时任务类。
举例:
springBoot启动类:
@EnableScheduling@SpringBootApplication@EnableAsyncpublic class StudyApplication {public static void main(String[] args) {SpringApplication.run(StudyApplication.class, args);}}
定时任务类:
@Componentpublic class ScheduleTaskDelay {@Scheduled(fixedRate = 3000)@Scheduled(fixedRate = 3000)@Asyncpublic void task(){System.out.println(Thread.currentThread().getName() + " start time is: " + new Date());System.out.println(Thread.currentThread().getName() + " is processing...");try {Thread.sleep(6000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + " schedule task is finished");System.out.println(Thread.currentThread().getName() + " end time is: " + new Date());}}
注意:
- 定时任务具体的执行情况可以通过@Schedule里的参数设置,比如fixedRate、fixedDelay和corn表达式;
- Schedule默认是单线程执行,如果需要异步模式,可以加上@Async注解。
12.1.2 cron表达式
cron表达式是一个字符串,作为@Schedule注解里的参数,用来制定粒度更为详细的定时任务,一个corn表达式是一个由六至七个字段组成由空格分隔的字符串,其中6个字段是必须的,而剩下的一个是可选的,corn表达式的位从左至右依次为:
| 字段名 | 允许的值 | 允许的特殊字符 |
|---|---|---|
| 秒 | 0-59 | , - * / |
| 分 | 0-59 | , - * / |
| 小时 | 0-23 | , - * / |
| 日 | 1-31 | , - * ? / L W C |
| 月 | 1-12 or JAN-DEC | , - * / |
| 周几 | 1-7 or SUN-SAT | , - * ? / L C # |
| 年 (可选字段) | empty, 1970-2099 | , - * / |
说明:
- ‘‘ 字符可以用于所有字段,在“分”字段中设为”“表示”每一分钟”的含义;
- ‘?’ 字符可以用在“日”和“周几”字段. 它用来指定 ‘不明确的值’. 这在你需要指定这两个字段中的某一个值而不是另外一个的时候会被用到。在后面的例子中可以看到其含义;
- ‘-‘ 字符被用来指定一个值的范围,比如在“小时”字段中设为”10-12”表示”10点到12点”;
- ‘,’ 字符指定数个值。比如在“周几”字段中设为”MON,WED,FRI”表示”the days Monday, Wednesday, and Friday”;
- ‘/‘ 字符用来指定一个值的的增加幅度. 比如在“秒”字段中设置为”0/15”表示”第0, 15, 30, 和 45秒”。而 “5/15”则表示”第5, 20, 35, 和 50”. 在’/‘前加”*”字符相当于指定从0秒开始. 每个字段都有一系列可以开始或结束的数值。对于“秒”和“分”字段来说,其数值范围为0到59,对于“小时”字段来说其为0到23, 对于“日”字段来说为0到31, 而对于“月”字段来说为1到12。”/“字段仅仅只是帮助你在允许的数值范围内从开始”第n”的值。 因此 对于“月”字段来说”7/6”只是表示7月被开启而不是“每六个月”, 请注意其中微妙的差别;
- ‘L’字符可用在“日”和“周几”这两个字段。它是”last”的缩写, 但是在这两个字段中有不同的含义。例如,“日”字段中的”L”表示”一个月中的最后一天” —— 对于一月就是31号对于二月来说就是28号(非闰年)。而在“周几”字段中, 它简单的表示”7” or “SAT”,但是如果在“周几”字段中使用时跟在某个数字之后, 它表示”该月最后一个星期×” —— 比如”6L”表示”该月最后一个周五”。当使用’L’选项时,指定确定的列表或者范围非常重要,否则你会被结果搞糊涂的;
- ‘W’ 可用于“日”字段。用来指定历给定日期最近的工作日(周一到周五) 。比如你将“日”字段设为”15W”,意为: “离该月15号最近的工作日”。因此如果15号为周六,触发器会在14号即周五调用。如果15号为周日, 触发器会在16号也就是周一触发。如果15号为周二,那么当天就会触发。然而如果你将“日”字段设为”1W”, 而一号又是周六, 触发器会于下周一也就是当月的3号触发,因为它不会越过当月的值的范围边界。’W’字符只能用于“日”字段的值为单独的一天而不是一系列值的时候;
- ‘L’和’W’可以组合用于“日”字段表示为’LW’,意为”该月最后一个工作日”;
- ‘#’ 字符可用于“周几”字段。该字符表示“该月第几个周×”,比如”6#3”表示该月第三个周五( 6表示周五而”#3”该月第三个)。再比如: “2#1” = 表示该月第一个周一而 “4#5” = 该月第五个周三。注意如果你指定”#5”该月没有第五个“周×”,该月是不会触发的;
- ‘C’ 字符可用于“日”和“周几”字段,它是”calendar”的缩写。 它表示为基于相关的日历所计算出的值(如果有的话)。如果没有关联的日历, 那它等同于包含全部日历。“日”字段值为”5C”表示”日历中的第一天或者5号以后”,“周几”字段值为”1C”则表示”日历中的第一天或者周日以后”;
- 对于“月份”字段和“周几”字段来说合法的字符都不是大小写敏感的。
常用的corn表达式举例:
| 含义 | corn表达式 |
|---|---|
| 每天中午十二点触发 | “0 0 12 ?” |
| 每天早上10:15触发 | “0 15 10 ? “ |
| 每天早上10:15触发 | “0 15 10 ?” |
| 每天早上10:15触发 | “0 15 10 ? *” |
| 2005年的每天早上10:15触发 | “0 15 10 ? 2005” |
| 每天从下午2点开始到2点59分每分钟一次触发 | “0 14 * ?” |
| 每天从下午2点开始到2:55分结束每5分钟一次触发 | “0 0/5 14 ?” |
| 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发 | “0 0/5 14,18 ?” |
| 每天14:00至14:05每分钟一次触发 | “0 0-5 14 ?” |
| 三月的每周三的14:10和14:44触发 | “0 10,44 14 ? 3 WED” |
| 每个周一、周二、周三、周四、周五的10:15触发 | “0 15 10 ? * MON-FRI” |
| 每月15号的10:15触发 | “0 15 10 15 * ?” |
| 每月的最后一天的10:15触发 | “0 15 10 L * ?” |
| 每月最后一个周五的10:15触发 | “0 15 10 ? * 6L” |
| 每月最后一个周五的10:15触发 | “0 15 10 ? * 6L” |
| 2002年至2005年的每月最后一个周五的10:15触发 | “0 15 10 ? * 6L 2002-2005” |
| 每月的第三个周五的10:15触发 | “0 15 10 ? * 6#3” |
12.1.3 使用注意点
由于@Schedule注解默认是单线程,这会给我们实际使用时带来一些“坑”,比如我用@Scheduled(fixedRate = 3000)建立了一个定时任务的方法,但是这个方法的实现,执行定时任务的时间大于fixedRate的值,结果就不是我们期望的每隔3秒都会执行一次任务,因为未执行的任务会被阻塞,因此需要异步地执行周期性任务。
将@Schedule注解的周期性任务异步化有两种方案:
- 使用@Async注解实现异步任务,这种方式比较简单,在定时任务的方法上加上@Async注解,注意启动类要加上@EnableAsync才会生效;
通过SchedulingConfigurer类手动设置定时任务的线程池大小,不使用@Async注解,如下:
@Configurationpublic class AppConfig implements SchedulingConfigurer {@Beanpublic Executor taskExecutor() {//指定定时任务线程数量,可根据需求自行调节return Executors.newScheduledThreadPool(3);}@Overridepublic void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {scheduledTaskRegistrar.setScheduler(taskExecutor());}}
两种方案各有优缺点:
| 比较 | 方案一 | 方案二 |
|---|---|---|
| 优点 | 注解方式使用简单,代码量少 | 配置灵活,线程数可控 |
| 缺点 | 线程数不可控,可能存在资源浪费 | 需要增加编码 |
12.2 @Async
上面介绍@Schedule注解的时候提到了@Async注解,这个注解就是SpringBoot提供异步功能的方案。使用时需要在springBoot启动类上添加**@EnableAsync**注解,在需要异步的方法上添加@Async注解,搭配CompletableFuture可以获得异步任务的执行结果。
举例:
controller:
package com.springboot.study.async.controller;import com.springboot.study.async.service.impl.AsyncServiceImpl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/study")public class AsyncController {@Autowiredprivate AsyncServiceImpl asyncService;@GetMapping("/async/something")public String asyncMethod() {asyncService.exampleMethod("Jerry");asyncService.exampleMethod("Tom");asyncService.exampleMethod("Cissie");asyncService.exampleMethod("Jack");return "sucess";}}
service:
package com.springboot.study.async.service.impl;import lombok.extern.slf4j.Slf4j;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;@Slf4j@Servicepublic class AsyncServiceImpl {@Asyncpublic String exampleMethod(String msg){log.info(Thread.currentThread().getName() + " 正在打印:{}", msg);try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}return msg;}}
用postman发请求:
http://localhost:8080/study/async/something
结果:
22:01:14.740 [pool-1-thread-4] INFO com.springboot.study.async.service.impl.AsyncServiceImpl - pool-1-thread-4 正在打印:Jack22:01:14.740 [pool-1-thread-1] INFO com.springboot.study.async.service.impl.AsyncServiceImpl - pool-1-thread-1 正在打印:Jerry22:01:14.740 [pool-1-thread-3] INFO com.springboot.study.async.service.impl.AsyncServiceImpl - pool-1-thread-3 正在打印:Cissie22:01:14.740 [pool-1-thread-2] INFO com.springboot.study.async.service.impl.AsyncServiceImpl - pool-1-thread-2 正在打印:Tom
从打印结果看,调用service里的exampleMethod方法已经是不同的线程再调用,实现了异步的效果。
如果想让指定的线程池执行异步任务,可以在@Async直接指定线程池名称:@Async(“线程池名称或者前缀”),详细的方法见参考链接。
**@Async**注解会在以下几个场景失效,也就是说明明使用了@Async注解,但就没有走多线程:
- 异步方法使用static关键词修饰;
- 异步类不是一个Spring容器的bean(一般使用注解
@Component和@Service,并且能被Spring扫描到); - SpringBoot应用中没有添加
@EnableAsync注解; - 在同一个类中,一个方法调用另外一个有@Async注解的方法,注解不会生效。原因是@Async注解的方法,是在代理类中执行的。
需要注意的是: 异步方法使用注解@Async的返回值只能为void或者Future及其子类,当返回结果为其他类型时,方法还是会异步执行,但是返回值都是null。
12.3 @EventListener
@EventListener是Springboot通过注解实现监听的一种方式,再介绍使用方法前, 先说一下监听机制:
监听机制用到了设计模式里的“观察者模式”,监听者ABC在监听一个事件,当事件发布者发布事件后,正在监听该事件的ABC会触发对应的处理逻辑。监听机制可以抽象出来三个模块:
- 被监听的事件;
- 事件发布;
- 监听者及监听者监听到事件后对应的处理逻辑。
当系统对并发要求比较高,或者出于更高层次的设计时,可以用消息队列来实现这种监听机制,但也会同时引入消息队列对应的复杂性问题。
这里以网上购物时下订单及支付订单为例说明监听机制及介绍@EventListener如何使用。网上选好商品时确定下单,然而实际如何支付这个订单,是用微信还是支付宝,是当场付钱还是半小时后付钱,说明如何支付订单是个复杂的逻辑,且下单和支付订单是两个应该解耦的逻辑,此时就可以使用监听机制(实际项目里应使用消息队列来实现监听机制),支付服务监听订单服务的下单事件,一旦监听到有下单任务,就触发支付服务执行支付业务。
举例:
订单服务类(对应事件发布者)
import lombok.extern.slf4j.Slf4j;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Service;@Slf4j@Servicepublic class OrderServiceImpl {/*** 这里传入ApplicationContext实例有点奇怪,实际项目中肯定不会传这个,* 传这个的目的是调用applicationContext.publishEvent方法触发监听的事件* @param applicationContext*/public void createOrder(ApplicationContext applicationContext){// 前面是创建订单的逻辑,后面是下单成功后的逻辑log.info(Thread.currentThread().getName() + " 下单成功");// 触发支付业务applicationContext.publishEvent(new OrderSuccessEvent(this, "下单成功"));log.info(Thread.currentThread().getName() + " 下单任务结束");}}
被监听/发布的事件:
package com.springboot.study.enentListener;import org.springframework.context.ApplicationEvent;public class OrderSuccessEvent extends ApplicationEvent {private String msg;public OrderSuccessEvent(Object source, String msg){super(source);this.msg = msg;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}
支付服务类(对应监听者及监听者监听到事件后对应的处理逻辑):
package com.springboot.study.enentListener;import lombok.extern.slf4j.Slf4j;import org.springframework.context.event.EventListener;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;@Slf4j@Servicepublic class PaymentImpl {@Async("doSomethingExecutor")@EventListenerpublic void eventListener(OrderSuccessEvent orderSuccessEvent){log.info(Thread.currentThread().getName() + " 开始支付业务");// 这里写具体支付业务逻辑log.info(Thread.currentThread().getName() + " 支付业务结束");}}
自定义异步线程池:
package com.springboot.study.enentListener;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;import java.util.concurrent.ThreadPoolExecutor;@Configuration@EnableAsyncpublic class AsyncConfiguration {@Bean("doSomethingExecutor")public Executor doSomethingExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// 核心线程数:线程池创建时候初始化的线程数executor.setCorePoolSize(10);// 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程executor.setMaxPoolSize(20);// 缓冲队列:用来缓冲执行任务的队列executor.setQueueCapacity(500);// 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁executor.setKeepAliveSeconds(60);// 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池executor.setThreadNamePrefix("do-something-");// 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程)executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());executor.initialize();return executor;}}
注意:
- 用publishEvent方法触发监听事件的发布,不一定用applicationContext调用;
- 监听事件要继承ApplicationEvent类;
- 监听方法用@EventListener注解修饰,且入参为监听事件类。
问题:当监听方法被@EventListener和@Aysnc注解修饰时,异步线程里的Thread.sleep方法会抛interruptedException异常?
参考链接
8000字的Spring/SpringBoot常用注解总结!安排!
Spring多定时任务@Scheduled执行阻塞问题
SpringBoot中如何优雅的使用多线程
cron表达式详解
spring中EventListener使用
Spring事件监听机制
到底什么是上下文?
https://www.yuque.com/zhangjian-mbxkb/zu7dxg/qgpomk#92qci
