Reputation: 1029
Possibly duplicate of Servlet not loading on startup, however Im not allowed yet to comment, so I have to start a new question for this...
Same setting, having a servlet using Jersey and Tomcat, using load-on-startup for loading the container. However, due to the thread mentioned above, I understand that this only load the Jersey container but not the classes I setup for the servlet.
So, related to what is implied in the answer of the thread above, how is it done that not only the contained is loaded at startup but also my classes which are annotated with @Path (which will e.g. load data from a DB in memory).
@Singleton
@Path( "156846986" )
public class SearchEngine {
@Inject
private DatabaseService dbService;
@Inject
private PatriciaTrieEngine trieEngine;
}
and for example:
@Singleton
@Path( "3455470640" )
public class PatriciaTrieEngine {
@Inject
DatabaseService dbService;
private PatriciaTrie< Object > patriciaTrie;
@PostConstruct
public void init( ) throws SQLException {
...some code initializing the trie by loading data from a database u using dbService
}
}
finally some classes like SearchService
have the endpoints for requests:
@Path( "/search" )
@Produces( "application/json" )
public class SearchService {
@Inject
private DatabaseService dbService;
@Inject
private SearchEngine engine;
@GET
@Path( "/candidates" )
public Response getCandidates(@QueryParam( "query" ) final String input) throws UnsupportedEncodingException {
use Patricia trie via SearchEngine in order to find candidates for given query
return Response.ok().entity( candidates ).build();
}
}
Ultimately it is the PatriciaTrie which should be loaded at startup as it takes several minutes to load the data into the trie.
Upvotes: 2
Views: 4518
Reputation: 208944
Default behavior is to instantiate a new instance of the resource class per request. In which case there isn't an expected need to load on start up. If you want this behavior, then your resource class needs to be a singleton, meaning only one instance is created for the whole application. If you do this, then you are responsible for making the class thread safe.
In Jersey 1, you can make the class a singleton with the @Singleton
annotation, as mentioned here. This will also load the class on start up. In Jersey 2, the @Singleton
annotation will make the resource class a singleton, but it will not load on start up. For that, you can instead use the @Immediate
annotation, as seen here
That aside, just from your description, this appears to me like maybe a need to fix the design. Can't really tell without seeing some code to what you're trying to do.
Upvotes: 4