ApplicationListener事件
有时候需要在项目初始化的时候进行一系列工作,比如初始化一个线程池,初始化配置文件,初始化缓存等等,这时候就需要用到启动监听器,applicationListener在使用过程中可以监听某一事件的发生,可以做出相应的处理,这个方式不常用,但是在特殊情况下面还是有用的。
通过查看源代码ApplicationEvent事件
上面是Spring启动可能发布的一些事件,这里介绍我讲介绍两个事件,EmbeddedServletContainerInitializedEvent,这个事件可以用来获取到Servlet容器启动的端口
/**
* 监听EmbeddedServletContainerInitializedEvent事件,用来获取Servlet容器初始化的端口
*
* @author will
* @author qianyi
* @author garen
* @since 1.0
*/
@Component
public class EmbeddedServletContainerInitializedEventListener implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
ServerPortHolder.setPort(event.getSource().getPort());
}
}
第二个事件是图中的ApplicationReadyEvent,通常如果我们想在应用程序启动之后获取一些启动信息,可以监听这个事件,然后完成一系列的事件,比如获取启动的ContextPath
,这里因为项目中集成了Swagger接口文档,在应用程序启动完成之后,我们可以打印出Swagger文档的访问路径
/**
* 应用程序启动监听,准备Swagger接口文档
*
* @author will
* @author qianyi
* @author garen
* @since 1.0
*/
@Component
public class ApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(ApplicationReadyListener.class);
@Autowired
private ServerProperties properties;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
LOGGER.debug("Application Ready");
String ctx = properties.getContextPath();
if (StringUtils.isEmpty(ctx)) {
ctx = "/";
} else {
ctx = ctx + "/";
}
String portPart = "";
Integer port = ServerPortHolder.getPort();
if (port!=80) {
portPart = ":" + port;
}
String host = null;
try {
host = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
// e.printStackTrace();
}
if (StringUtils.isEmpty(host)) {
host = "127.0.0.1";
}
String message = String.format("Access URLS: External: %s%s%s%s%s", "http://", host, portPart, ctx, "swagger-ui.html");
message+= String.format(" , %s%s%s%s%s", "http://", host, portPart, ctx, "");
LOGGER.info(message);
}
}
这里我们可以看到,启动之后,我们的Console会打印出我们的访问地址: