我的需求是獲取spring開發(fā)的web項目在服務(wù)器上的絕對路徑。
進而引申到我需要知道servletContext,因為servletContext有一個servletContext.getRealPath("/");方法,這個方法就能獲取項目的絕對路徑。
常規(guī)方式下我們?nèi)绾潍@取servletContext呢?我們需要讓我們的類繼承HttpServlet類,然后獲取servletConfig,通過這個獲取servletContext(servletConfig.getServletContext())。(至于如何獲取servletconfig對象,大家去google,百度找找吧)
但是我需要在spring的bean中直接獲取,這下可和我們常規(guī)的操作有些不同,因為spring的bean都是pojo的。根本見不著servletconfig和servletcontext的影子。
這里我需要指出spring給我們提供了兩個接口:org.springframework.web.context.ServletContextAware和
org.springframework.web.context.ServletConfigAware。我們可以讓我們的bean實現(xiàn)上邊的任何一個接口就能獲取到servletContext了 .
代碼如下:
這樣,我們的bean就能夠直接獲取到servletContext了
如果你想要servletConfig,那方法一樣,只是實現(xiàn)的接口不同了。
原理推想:應(yīng)該是在創(chuàng)建spring的sessionFactory的時候,將應(yīng)用服務(wù)器的相關(guān)屬性一并加載,查看創(chuàng)建的bean是否實現(xiàn)相關(guān)接口,如果實現(xiàn)了,就將相關(guān)值賦予bean。
注意點:
1、這東西是無法用junit進行單元測試的,因為他依賴于應(yīng)用服務(wù)器
進而引申到我需要知道servletContext,因為servletContext有一個servletContext.getRealPath("/");方法,這個方法就能獲取項目的絕對路徑。
常規(guī)方式下我們?nèi)绾潍@取servletContext呢?我們需要讓我們的類繼承HttpServlet類,然后獲取servletConfig,通過這個獲取servletContext(servletConfig.getServletContext())。(至于如何獲取servletconfig對象,大家去google,百度找找吧)
但是我需要在spring的bean中直接獲取,這下可和我們常規(guī)的操作有些不同,因為spring的bean都是pojo的。根本見不著servletconfig和servletcontext的影子。
這里我需要指出spring給我們提供了兩個接口:org.springframework.web.context.ServletContextAware和
org.springframework.web.context.ServletConfigAware。我們可以讓我們的bean實現(xiàn)上邊的任何一個接口就能獲取到servletContext了 .
代碼如下:
這樣,我們的bean就能夠直接獲取到servletContext了
如果你想要servletConfig,那方法一樣,只是實現(xiàn)的接口不同了。
原理推想:應(yīng)該是在創(chuàng)建spring的sessionFactory的時候,將應(yīng)用服務(wù)器的相關(guān)屬性一并加載,查看創(chuàng)建的bean是否實現(xiàn)相關(guān)接口,如果實現(xiàn)了,就將相關(guān)值賦予bean。
注意點:
1、這東西是無法用junit進行單元測試的,因為他依賴于應(yīng)用服務(wù)器