2013-05-12 88 views
6

我正在創建一個包裝陳舊的供應商API的RESTful Web服務。一些外部配置將是必需的,並將以文件或rdbms的形式存儲在服務器上。我在Glassfish 3.1.2中使用Jersey 1.11.1。此配置數據全部採用字符串鍵/值格式。如何在Jersey/Glassfish中加載和存儲全局變量

我的第一個問題是 - 我在哪裏可以將全局/實例變量存儲在澤西島,以便它們將在請求之間保持並可用於所有資源?如果這是一個純粹的Servlet應用程序,我會使用ServletContext來實現這一點。

問題的第二部分是如何在澤西服務器加載後加載我的配置?同樣,我的Servlet比喻是找到與init()方法等價的東西。

回答

11

@Singleton @Startup EJB符合您的要求。

@Singleton 
@Startup // initialize at deployment time instead of first invocation 
public class VendorConfiguration { 

    @PostConstruct 
    void loadConfiguration() { 
     // do the startup initialization here 
    } 

    @Lock(LockType.READ) // To allow multiple threads to invoke this method 
         // simultaneusly 
    public String getValue(String key) { 
    } 
} 


@Path('/resource') 
@Stateless 
public class TheResource { 
    @EJB 
    VendorConfiguration configuration; 
    // ... 
} 

編輯:添加註釋按照格雷厄姆的評論

+0

這看起來像一個很好的解決方案,它在加載時運行正常,但當我嘗試在我的Resource類中引用此EJB時,我得到一個InvocationTargetException(由容器顯示爲NullPointerException)。 – Graham 2013-05-12 20:37:17

+0

來自Jersey郵件列表:_By不支持默認注入EE資源,除非您將資源轉換爲託管bean(並且請注意,將資源類轉換爲託管bean時有一些限制)._ – Graham 2013-05-12 22:21:11

+0

一旦我添加了@Stateless標誌我的資源,這工作完美,絕對是一個很好的解決方案。這兩頁幫助我更好地理解了這些概念:[EJB 3.1和REST - 輕量級混合](http://www.adam-bien.com/roller/abien/entry/ejb_3_1_and_rest)[Singletons](https ://blogs.oracle.com/kensaks/entry/singletons) – Graham 2013-05-13 16:15:02

7

可以使用listener init的變量,並設置爲背景的Web應用程序開始之前的屬性,像下面的內容:

package org.paulvargas.shared; 

import java.util.HashMap; 
import java.util.Map; 

import javax.servlet.ServletContext; 
import javax.servlet.ServletContextEvent; 
import javax.servlet.ServletContextListener; 

public class LoadConfigurationListener implements ServletContextListener { 

    public void contextInitialized(ServletContextEvent sce) { 
     // read file or rdbms 
     ... 
     ServletContext context = sce.getServletContext(); 
     // set attributes 
     ... 
    } 

    public void contextDestroyed(ServletContextEvent sce) { 
     ServletContext context = sce.getServletContext(); 
     // remove attributes 
     ... 
    } 

} 

此偵聽器在web.xml配置。

<listener> 
    <listener-class>org.paulvargas.shared.LoadConfigurationListener</listener-class> 
</listener> 

可以使用@Context標註爲注入ServletContext和檢索的屬性。

package org.paulvargas.example.helloworld; 

import java.util.*; 

import javax.servlet.ServletContext; 
import javax.ws.rs.*; 
import javax.ws.rs.core.*; 

@Path("/world") 
public class HelloWorld { 

    @Context 
    private ServletContext context; 

    @GET 
    @Produces("text/plain; charset=UTF-8") 
    public String getGreeting() { 

     // get attributes 
     String someVar = (String) context.getAttribute("someName") 

     return someVar + " says hello!"; 
    } 

} 
+0

這無疑是一個可行的解決方案,但它涉及添加一個web.xml,我現在有沒有和一些額外的工作,以濾除ServletContext中存在的其他屬性。我給了這個讚賞,但不得不將答案授予另一篇文章,因爲它既簡單又多功能。 – Graham 2013-05-13 18:12:50

相關問題