package com.csnf.config;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.io.InputStream;

@WebListener
public class MyServletContextListener implements ServletContextListener {
    private Logger logger = Logger.getLogger(MyServletContextListener.class);
    public void contextInitialized(javax.servlet.ServletContextEvent servletContextEvent) {
        InputStream input = null;
        try{
            input = Resources.getResourceAsStream("mybatis-config.xml");
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(input);

        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ServletContext application= servletContextEvent.getServletContext();
        application.setAttribute("sqlSession", sqlSession);
        logger.info("初始化成功:"+sqlSession);
    }
    public void contextDestroyed(javax.servlet.ServletContextEvent servletContextEvent) {

    }
}
