I want to initialize the Jersey Rest service and enter a global application variable that should be calculated when the application starts, and should be available in each rest resource and each method (here is an integer globalAppValue = 17, but it will be a complex object later).
To initialize the service and calculate the value once at startup, I found two methods: the generic ServletContextListener method and the ResourceConfig method in Jersey. But I did not understand what is the difference between them? Both methods start at startup (both System.out messages are printed).
Here is an implementation of my ServletContextListener that works fine:
public class LoadConfigurationListener implements ServletContextListener
{
private int globalAppValue = 17;
@Override
public void contextDestroyed (ServletContextEvent event)
{
}
@Override
public void contextInitialized (ServletContextEvent event)
{
System.out.println ("ServletContext init.");
ServletContext context = event.getServletContext ();
context.setAttribute ("globalAppValue", globalAppValue);
}
}
Jersey Rest ResourceConfig, ServletContext . - :
@ApplicationPath("Resources")
public class MyApplication extends ResourceConfig
{
@Context
ServletContext context;
private int globalAppValue = 17;
public MyApplication () throws NamingException
{
System.out.println ("Application init.");
context.setAttribute ("globalAppValue", 17);
}
public int getAppValue ()
{
return globalAppValue;
}
}
:
@Path("/")
public class TestResource
{
@Context
ServletContext context;
@Context
MyApplication application;
@Path("/test")
@GET
public String sayHello () throws SQLException
{
String result = "Hello World: ";
result += "globalAppValue=" + application.getAppValue ();
result += "contextValue=" + context.getAttribute ("globalAppValue");
return result;
}
}
, ServletContextListener , ResourceConfig/Application, , , , . , . !