Spring等效于在容器启动后加载主数据的servlet

时间:2015-01-28 03:46:24

标签: spring spring-mvc servlets

我的webapp中有一个servlet(基于MVC Model 2),它在tomcat容器加载应用程序上下文后加载所有主数据。我想用基于Spring的解决方案替换它。请注意,它需要访问数据源。我怎么能这样做?

的web.xml

 <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>

MasterDataLoader.java

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;
    }
}

1 个答案:

答案 0 :(得分:0)

使用@PostConstruct注释其中一个bean的方法,并使用此方法完成工作。 the documentation中提供的示例正是您想要做的事情。