How do I load and store global variables in Jersey / Glassfish

advertisements

I am creating a RESTful Web Service that wraps an antiquated vendor API. Some external configuration will be required and will be stored on the server either in a file or rdbms. I'm using Jersey 1.11.1 in Glassfish 3.1.2. This configuration data is all in String key/value format.

My first question is this - where can I store global/instance variables in Jersey so that they will be persisted between requests and available to all resources? If this was a pure Servlet application I would use the ServletContext to accomplish this.

The second part to the question is how can I load my configuration once the Jersey server has loaded? Again, my Servlet analogy would be to find the equivalent to the init() method.


@Singleton @Startup EJB matches your requirements.

@Singleton
@Startup // initialize at deployment time instead of first invocation
public class VendorConfiguration {

    @PostConstruct
    void loadConfiguration() {
        // do the startup initialization here
    }

    @Lock(LockType.READ) // To allow multiple threads to invoke this method
                         // simultaneusly
    public String getValue(String key) {
    }
}

@Path('/resource')
@Stateless
public class TheResource {
    @EJB
    VendorConfiguration configuration;
    // ...
}

EDIT: Added annotation as per Graham's comment