Creating an application scoped bean in spring MVC
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开发者_StackOverflow中文版 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.
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);
}
}
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:
- The controller is wired up with an instance of the
MyService
interface which has operations for retrieving the data in question.- Optionally, depending on if you separate your DAO layer from your service layer, the
MyService
implementation is wired up with aMyDAO
bean.
- Optionally, depending on if you separate your DAO layer from your service layer, the
- The
MyService
implementation is marked asInitializingBean
, and in theafterPropertiesSet()
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
.
精彩评论