[英]Create servlet context without autowiring in spring
我有一個單例類,其中一個私有成員是ServletContext對象。 由於要嘗試使用純Java代碼編寫代碼,因此我單身刪除了spring依賴項。
public class Utils {
private static Utils utils = null;
public Utils() {
// Exists only to defeat instantiation.
}
public synchronized static Utils getInstance() {
if (utils == null) {
utils = new Utils();
}
return utils;
}
@Autowired
private ServletContext servletContext;
public void makeUtils() {
// output csv path
String outputFile = servletContext.getRealPath("/util");
}
}
但是這里的servletContext
將為null,因為無論我在哪里需要手動創建Utils
類的對象。 不能通過使用@Autowired。 因此,spring不會注入依賴。 我該如何解決。
@Autowired
是一個彈簧注釋。
如果您希望響應該批注而發生某些事情,則需要使用spring。 如果要刪除對spring的依賴,則不能使用Autowired
。 您需要選擇一個-接線是否要依靠彈簧?
您可以遵循的一些解決方案:
Utils
成為四季豆並注入 將Utils
放入您的spring上下文(bean工廠),然后將其(使用@Autowired
或其他接線策略)注入到其他要使用它的類中。
Utils
成為四季豆,然后將其查找。 確實沒有太多理由這樣做,但是如果您願意,可以訪問您的spring bean工廠(可能通過ApplicationContext
)並使用BeanFactory.getBean(Class<T>)
按類型查找bean。
Utils
對象 同樣,這樣做的理由並不多,但是如果您有一個AutowireCapableBeanFactory
實例(可以通過ApplicationContext
獲取),則可以調用autowireBean(Object existingBean)
來獲取彈簧以連接@Autowired
字段。
注意:我的方法/類引用來自Spring 3.2,因為它是我的IDE中現在打開的東西。 如果您使用的是其他春季版本,則可能需要進行調整)
Utils
在采用ServletContext
Utils
上創建一個configure
方法。
在Servlet
(或ServletContextListener
)調用中,該調用configure
方法設置Utils
上的servletContext
字段。
ServletContext
創建一個像ServletContextHolder
這樣的對象,該對象具有一個靜態字段,您可以在該字段上存儲ServletContext
到Servlet
(或ServletContextListener
)內部,在該持有者上調用setContext
方法來設置servletContext
字段。
在Utils
內部調用ServletContextHolder.getContext()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.