早期業(yè)務緊急峰锁,沒有過多的在意項目的運行效率,現(xiàn)在回過頭看走查代碼掷邦,發(fā)現(xiàn)后端項目(Spring MVC+MyBatis)在啟動過程中多次解析mybatis的xml配置文件及初始化數(shù)據(jù)挺庞,對開發(fā)階段開發(fā)人員反復啟停項目造成很大的時間浪費,也即是下面的第一種方式括儒。
1.Servlet方式
@Component
public class InitDataServlet extends HttpServlet {
? ?private static final Logger LOGGER = Logger.getLogger(InitDataServlet.class);
? ?static AbstractApplicationContext ctx;
? ?static {
? ? ? ?ctx = new FileSystemXmlApplicationContext("classpath:conf/spring*.xml");
? ?}
? ?/**
? ? * serialVersionUID:
? ? *
? ? * @since JDK 1.6
? ? */
? ?private static final long serialVersionUID = 1L;
? ?/**
? ? * 初始化數(shù)據(jù)
? ? *
? ? * @see javax.servlet.GenericServlet#init()
? ? */
? ?public void init() throws ServletException {
? ? ? ?loadBaseData();
? ?}
}
這種方式應該是比較常見的,上述代碼之所以這么寫锐想,是因為Servlet中無法使用使用Spring容器的上下文帮寻,只能在servlet中重新獲取,這也就導致了兩次容器的加載赠摇,與之相對應就是兩次相關程序的調(diào)用固逗。
以上代碼浅蚪,并結(jié)合web.xml中配置load-on-startup值為0,可以在項目啟動后立即執(zhí)行InitDataServlet方法烫罩。
后期優(yōu)化成InitializingBean的方式重構(gòu)惜傲,啟動速度上更快一步。下面簡單介紹下兩種方式
2.InitializingBean方式
@Component
public class InitDataServlet implements InitializingBean {
?private static final Logger LOGGER = Logger.getLogger(InitDataServlet.class);
?@Override
?public void afterPropertiesSet() throws Exception {
? ?loadBaseData();
?}
}
application.xml配置文件
3.ApplicationListener方式
@Component
public class InitDataServlet implements ApplicationListener {
?private static final Logger LOGGER = Logger.getLogger(InitDataServlet.class);
?@Override
?public void onApplicationEvent(ContextRefreshedEvent event) {
? ? ? ?//第一種方式
? ? ? ?//if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) {
? ? ? ? ? ?//TODO 編寫自己的初始化數(shù)據(jù)方法
? ? ? ?//}
? ? ? ?//第二種
? ? ? ?if(event.getApplicationContext().getParent() == null){
? ? ? ? ? ?//TODO 編寫自己初始化數(shù)據(jù)的方法
? ? ? ?}
?}
}
方法體內(nèi)有一個if分支只是為了規(guī)避onApplicationEvent方法執(zhí)行多次贝攒,在Spring MVC的項目中盗誊,系統(tǒng)會存在兩個容器,一個是Root WebApplicationContext ,另一個就是我們自己的WebApplicationContext(作為Root WebApplicationContext的子容器)隘弊,若不加以判斷哈踱,會給系統(tǒng)造成不必要的負載或邏輯上的錯誤等等。
如果你還在使用第一種方式的話梨熙,建議重構(gòu)為后兩種方式嚣鄙。
擴展閱讀: