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