Spring Boot启动后初始化相关数据

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 the org.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));     
		} 
	} 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值