Reputation: 11
Good day Everyone,
I want to explain my current legacy application before i ask my question. I have a servlet in a Tomcat in which i load a non-changing database table into memory in the init() using Hibernate. Because this is defined in the init(), it is called only once and its available across all subsequent requests to the servlet, this is used because it improved application performance because of less round trips to the database.
I have recently started to use Spring 3 and i want to change this set up (servlet class is now a controller) to Spring but my challenge is how do i create the ArrayList of domain object (as i do in the init()) at Spring load time for efficiency and have it available across all calls to the controller class without accessing the database every time a request comes in. If this is not possible, then what options do i have?
Any help would be very appreciated.
Upvotes: 1
Views: 1276
Reputation: 140051
how do i create the ArrayList of domain object (as i do in the init()) at Spring load time for efficiency and have it available across all calls to the controller class without accessing the database every time a request comes in. If this is not possible, then what options do i have?
I would design this almost identically in your scenario as I would if the data was constantly changing and had to be read from the database on each request:
MyService
interface which has operations for retrieving the data in question.
MyService
implementation is wired up with a MyDAO
bean.MyService
implementation is marked as InitializingBean
, and in the afterPropertiesSet()
method you retrieve the one-time-load data from the database.With this design, your controller does not know where it's data is coming from, just that it asks a MyService
implementation for the data. The data is loaded from the database when the MyService
implementing bean is first created by the Spring container.
This allows you to easily change the design to load the data on each request (or to expire the data at certain times, etc) by swapping in a different implementation of MyService
.
Upvotes: 0
Reputation: 13002
Pop that static data into the RequestInterceptor
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
....
modelAndView.addObject("variableName", dataIWantToHaveAvailableAllOverThePlace);
....
super.postHandle(request, response, handler, modelAndView);
}
}
Upvotes: 2