Stack Exchange
Glassfish 4.1invoke method on the server's startup?
I'm using Glassfish 4.1 to deploy a RESTful webapp using jersey 2.23.2.
What I'm trying to do is run a method at the server's startup
my 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> 

and 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
    }
}


I guess your solution is not working because your class is not managed by the container and therefore the @PostConstruct doesn't get evaluated.
You can try the following:
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
    }
}

If this isn't working here is a "real" solution:
@Singleton
@Startup
public class InitializerBean {

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

}

See also:

The Lifecycles of Enterprise Beans
Seven ways to get things started. Java EE Startup Classes with GlassFish and WebLogic
@Singleton, @Startup, @PostConstruct doesn't work on EJB3.1 and Glassfishv3.0.1

