2011-04-12 84 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>