spring boot实战(第二篇)事件监听
前言
spring boot在启动过程中增加事件监听机制,为用户功能拓展提供极大的便利。
支持的事件类型四种
ApplicationStartedEvent
ApplicationEnvironmentPreparedEvent
ApplicationPreparedEvent
ApplicationFailedEvent
实现监听步骤:
1.监听类实现ApplicationListener
接口
2.将监听类添加到SpringApplication
实例
ApplicationStartedEvent
ApplicationStartedEvent
:spring boot启动开始时执行的事件
创建对应的监听类 MyApplicationStartedEventListener.Java
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
在该事件中可以获取到SpringApplication
对象,可做一些执行前的设置.
Application.java
类
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
ApplicationEnvironmentPreparedEvent
ApplicationEnvironmentPreparedEvent
:spring boot 对应Enviroment已经准备完毕,但此时上下文context还没有创建。
MyApplicationEnvironmentPreparedEventListener.java
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
在该监听中获取到ConfigurableEnvironment
后可以对配置信息做操作,例如:修改默认的配置信息,增加额外的配置信息等等~~~
ApplicationPreparedEvent
ApplicationPreparedEvent
:spring boot上下文context创建完成,但此时spring中的bean是没有完全加载完成的。
MyApplicationPreparedEventListener.java
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
在获取完上下文后,可以将上下文传递出去做一些额外的操作。
在该监听器中是无法获取自定义bean并进行操作的。
ApplicationFailedEvent
ApplicationFailedEvent
:spring boot启动异常时执行事件
MyApplicationFailedEventListener.java
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
在异常发生时,最好是添加虚拟机对应的钩子进行资源的回收与释放,能友善的处理异常信息。
在spring boot中已经为大家考虑了这一点,默认情况开启了对应的功能:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
在doClose()
方法中进行资源的回收与释放。
结束语
spring boot提供的四种监听事件到这里就结束了,针对实际业务可添加自定义的监听器,下一节当中将会对spring boot中的监听源码进行分析,理解为什么是这样的。
转载请注明
http://blog.csdn.net/liaokailin/article/details/48186331