Spring容器是生成Bean的工廠,我們?cè)谧鲰?xiàng)目的時(shí)候,會(huì)用到監(jiān)聽器去獲取spring的配置文件,然后從中拿出我們需要的bean出來,比如做網(wǎng)站首頁,假設(shè)商品的后臺(tái)業(yè)務(wù)邏輯都做好了,我們需要?jiǎng)?chuàng)建一個(gè)監(jiān)聽器,在項(xiàng)目啟動(dòng)時(shí)將首頁的數(shù)據(jù)查詢出來放到application里,即在監(jiān)聽器里調(diào)用后臺(tái)商品業(yè)務(wù)邏輯的方法,也就是說我們需要在監(jiān)聽器里獲取Spring中配置的相應(yīng)的bean。先把監(jiān)聽器創(chuàng)建出來:
1. 創(chuàng)建InitDataListener
創(chuàng)建一個(gè)監(jiān)聽器InitDataListener繼承ServletContextListener:
1 //@Component //監(jiān)聽器是web層的組件,它是tomcat實(shí)例化的,不是Spring實(shí)例化的。不能放到Spring中 2 public class InitDataListener implements ServletContextListener { 3 4 private ProductService productService = null;//productService中定義了跟商品相關(guān)的業(yè)務(wù)邏輯 5 6 @Override 7 public void contextDestroyed(ServletContextEvent event) { 8 9 } 10 11 @Override 12 public void contextInitialized(ServletContextEvent event) { 13 14 } 15 1