我的webapp中有一个servlet(基于MVC Model 2),它在tomcat容器加载应用程序上下文后加载所有主数据。我想用基于Spring的解决方案替换它。请注意,它需要访问数据源。我怎么能这样做?
<servlet>
<description>Loads all master data for the application to reduce response time</description>
<servlet-name>MasterDataLoader</servlet-name>
<servlet-class>com.mywebapp.web.controllers.MasterDataLoader</servlet-class>
<load-on-startup>10</load-on-startup>
</servlet>
public class MasterDataLoader extends HttpServlet {
private static final Logger LOG = Logger.getLogger(MasterDataLoader.class);
private static final String DATASOURCE = "dataSource";
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
loadAll();
}
private void loadAll() {
LOG.debug("Fetching all master data (menu categories, states, freight companies, tender types, product cross sells, best sellers etc.) for the application.........");
ServletContext appContext = getServletContext();
appContext.setAttribute("states", getAllStates());
}
private List<State> getAllStates() {
LOG.debug("Fetching all states from db...");
List<State> statesLst = null;
try {
DataSource dataSource = (DataSource) getServletContext().getAttribute(DATASOURCE);
statesLst = new MasterDao(dataSource).getAllStates();
} catch (SQLException ex) {
LOG.error("Exception while fetching all states...");
LOG.error(ex);
}
return statesLst;
}
}