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