2011-04-12 63 views

回答

3

您可以使用在Application#getSingletons()中定義的單例對象。

public class MyApp extends Application 
{ 
    public Set<Class<?>> getClasses() 
    { 
     return null; 
    } 

    public Set<Object> getSingletons() 
    { 
     Set<Object> set = new HashSet<Object>(); 
     Foo foo = /* init foo somehow */; 
     set.add(foo); 
     return set; 
    } 
} 

RESTful Java(如果你有這本書,見第142頁):

getSingletons()方法返回的預分配的JAX-RS Web服務和@Provider -annotated類的列表。作爲應用程序員,您負責創建這些對象。 JAX-RS運行時將迭代對象列表並在內部註冊它們。當這些對象被註冊時,JAX-RS也將注入@Context註釋字段和setter方法的值。

1

一般來說,球衣是由maven構建的。所以,當你執行maven命令時,會生成一個已初始化的項目。

mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 \ 
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \ 
-DgroupId=com.example -DartifactId=simple-service -Dpackage=com.example \ 
-DarchetypeVersion=2.4.1 

更多信息請訪問: https://jersey.java.net/documentation/latest/index.html

0

你可以寫一個實現了ServletContextListener類。

public class MyContextListener implements ServletContextListener { 
     @Override 
     public void contextInitialized(ServletContextEvent event) { 
      //stuff that happens when server is started 
     } 

     @Override 
     public void contextDestroyed(ServletContextEvent event) { 
      //stuff that happens when server is turned off 
     } 
    } 

然後,您只需將此添加到您的web.xml文件中作爲web應用程序元素的子項。

<listener> 
    <listener-class>com.mypackage.MyContextListener</listener-class> 
</listener>