Glassfish 4.1invoke方法在服务器的启动?

时间:2016-08-30 10:32:46

标签: java jersey glassfish jersey-2.0 glassfish-4.1

我使用Glassfish 4.1使用jersey 2.23.2部署RESTful webapp。

我尝试做的是在服务器启动时运行方法

我的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
    }
}

1 个答案:

答案 0 :(得分: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
   }

}

另见: