Spring Boot如何在启动后访问数据库并将数据库中的数据作为全局应用程序共享对象存储到ServletContext中。
使用Spring Boot的监听器
查看Spring Boot的官方文档,其内容有如下一段:
If you want those listeners to be registered automatically, regardless of the way the application is created, you can add a
META-INF/spring.factories
file to your project and reference your listener(s) by using theorg.springframework.context.ApplicationListener
key, as shown in the following example:org.springframework.context.ApplicationListener=com.example.project.MyListener
由上述可以知道,实现自动注册的监听器,可以通过实现ApplicationListener
接口,实现其中的方法完成监听器的注册。
在进行监听器注册时选择的触发事件类型是:ApplicationStartedEvent
,在官方文档中的解释如下 :
An
ApplicationReadyEvent
is sent after any application and command-line runners have been called. It indicates that the application is ready to service requests.
可以知道事件触发的时机是在Spring Boot启动后,而用户请求发送之前触发。
程序如下:
其中BlogSetting
为实体类,BlogSettingService
为MVC模式中的Service层(这两点不必深究,仅仅为了写个示例程序)
@Componentpublic
class BlogSettingInit implements ApplicationListener {
@Autowired
private BlogSettingService blogSettingService;
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
ServletContext servletContext = ((WebApplicationContext) applicationReadyEvent.getApplicationContext()).getServletContext();
List blogSettings = blogSettingService.findBlogSetting();
if (blogSettings.isEmpty() || blogSettings == null) {
BlogSetting blogSetting = new BlogSetting();
BlogSetting blogSetting1 = blogSettingService.BlogSettingSaveOrUpdate(blogSetting);
blogSetting.setId(blogSetting1.getId());
servletContext.setAttribute("setting", blogSetting);
} else {
servletContext.setAttribute("setting", blogSettings.get(0));
}
}
}
实现方式除上述一种外 ,亦可以使用注解的方式:
@Component
public class BlogSettingInit {
@Autowired
private BlogSettingService blogSettingService;
@EventListener
public void init(ApplicationReadyEvent applicationReadyEvent) {
ServletContext servletContext = ((WebApplicationContext)applicationReadyEvent.getApplicationContext()).getServletContext();
List blogSettings = blogSettingService.findBlogSetting();
if (blogSettings.isEmpty() || blogSettings == null) {
BlogSetting blogSetting = new BlogSetting();
BlogSetting blogSetting1 = blogSettingService.BlogSettingSaveOrUpdate(blogSetting);
blogSetting.setId(blogSetting1.getId());
servletContext.setAttribute("setting", blogSetting);
} else {
servletContext.setAttribute("setting", blogSettings.get(0));
}
}
}