天天看點

java類中擷取ServletContext的方法

在項目中遇到這樣一個問題,需要在沒有web請求的java普通類中,擷取ServletContext,那麼該怎麼擷取呢?

答案就是通過ContextLoader類:

WebApplicationContext webAc= ContextLoader.getCurrentWebApplicationContext();    

ServletContext servletContext = webAc.getServletContext();