Java Web(6)論如何在 Listener獲取Spring Bean

1. 在Web系統開始運行前,須要在數據庫裏填充一些預置的數據。這裏就須要一個在系統運行時,只運行一次的方法,來實現系統的初始化過程。
html

    在這裏,天然而然的想到了ServletContextListener這麼一個監聽器,在serlvet-api文檔是這麼描述的
java

    Interface for receiving notification events about ServletContext lifecycle changes.web

    而恰好,一個web系統,就只有一個servletContext。
spring

2. 而後問題來了,spring的初始化,加載xml配置也是使用這個麼一個監聽器——org.springframework.web.context.ContextLoaderListener。數據庫

    那要怎麼樣才能在本身定義的Listener中經過spring ApplicationContext來獲取Bean呢?
api

3. 答案就是WebApplicationContextUtils。這是spring-web裏的一個組件,能夠使用它來獲取ApplicationContext,在獲得了ApplicationContext,天然而然就得了Beanoracle

相關文章
相關標籤/搜索