2016-08-30 145 views
0

我使用Glassfish 4.1,使用球衣2.23.2來部署RESTful webapp。Glassfish 4.1在服務器啓動時啓動方法?

我試圖做的是運行在服務器的啓動

我的web.xml的方法

<!DOCTYPE web-app PUBLIC 
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
"http://java.sun.com/dtd/web-app_2_3.dtd" > 
<web-app> 
    <display-name>XYZ</display-name> 
    <servlet> 
     <servlet-name>MyApplication</servlet-name> 
     <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
     <init-param> 
      <param-name>javax.ws.rs.Application</param-name> 
      <param-value>MyApplication</param-value> 
     </init-param> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>MyApplication</servlet-name> 
     <url-pattern>/*</url-pattern> 
    </servlet-mapping> 

</web-app> 

和MyApplication.java

import javax.annotation.PostConstruct; 
import org.glassfish.jersey.server.ResourceConfig; 

public class MyApplication extends ResourceConfig { 
    public MyApplication() { 
     packages("services"); 
    } 

    @PostConstruct 
    public void post_construct() { 
     //The method I want to run 
    } 
} 

回答

0

我猜你的解決方案不工作,因爲您的班級不受容器管理,因此@PostConstruct未得到評估。

你可以嘗試以下方法:

import javax.annotation.PostConstruct; 
import org.glassfish.jersey.server.ResourceConfig; 

public class MyApplication extends ResourceConfig { 
    public MyApplication() { 
     packages("services"); 
     post_construct(); // <-- here is the call 
    } 

    @PostConstruct 
    public void post_construct() { 
     //The method I want to run 
    } 
} 

如果這不是在這裏工作是一個 「真實」 的解決方案:

@Singleton 
@Startup 
public class InitializerBean { 

    @PostConstruct 
    public void onStartup() { 
     // do your method-call here 
    } 

} 

參見: