簡體   English   中英

在春天沒有自動裝配的情況下創建servlet上下文

[英]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 您需要選擇一個-接線是否要依靠彈簧?

您可以遵循的一些解決方案:

使用Spring

使Utils成為四季豆並注入

Utils放入您的spring上下文(bean工廠),然后將其(使用@Autowired或其他接線策略)注入到其他要使用它的類中。

使Utils成為四季豆,然后將其查找。

確實沒有太多理由這樣做,但是如果您願意,可以訪問您的spring bean工廠(可能通過ApplicationContext )並使用BeanFactory.getBean(Class<T>)按類型查找bean。

使用Spring自動連接現有的Utils對象

同樣,這樣做的理由並不多,但是如果您有一個AutowireCapableBeanFactory實例(可以通過ApplicationContext獲取),則可以調用autowireBean(Object existingBean)來獲取彈簧以連接@Autowired字段。

注意:我的方法/類引用來自Spring 3.2,因為它是我的IDE中現在打開的東西。 如果您使用的是其他春季版本,則可能需要進行調整)

沒有春天

Servlet (或偵聽器)中實例化Utils

在采用ServletContext Utils上創建一個configure方法。
Servlet (或ServletContextListener )調用中,該調用configure方法設置Utils上的servletContext字段。

存儲靜態全局ServletContext

創建一個像ServletContextHolder這樣的對象,該對象具有一個靜態字段,您可以在該字段上存儲ServletContextServlet (或ServletContextListener )內部,在該持有者上調用setContext方法來設置servletContext字段。
Utils內部調用ServletContextHolder.getContext()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM