1:自定义监听器 集成ContextLoaderListener,

2: 在web.xml中配置监听器


作用:

在启动Web容器时,自动装配spring applicationContext.xml的配置信息。

因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成

web.xml

<listener>
    <listener-class>xx.listener.StartupListener</listener-class>
</listener>
**
 * 系统启动器
 * 
 */
public class StartupListener extends ContextLoaderListener {
    //log
    private final static Logger logger = LoggerFactory.getLogger(StartupListener.class);

    @Override
    public void contextInitialized(ServletContextEvent event) {
        logger.info("startup listener  ........");
        //获取Servlet上下文
        ServletContext sct = event.getServletContext();
        //获取Spring应用上下文
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sct);
        //静态常量持有Spring上下文
        SpringUtil.initial(sct, ctx);
        //SCM初始化
        PassengerFlowDataSCMConfig.getInstance();
        logger.info("startup listener success ........");
    }
}
SpringUtil工具类:

/**
 * Spring工具类
 * 
 */
public class SpringUtil {
    //Logger
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringUtil.class);
    //保持Spring上下文
    private static ApplicationContext ctx = null;
    //保持Servlet上下文
    private static ServletContext sct = null;

    /**
     * 初始化上下文
     *
     * @param newSct Servlet上下文
     * @param newCtx 系统启动时传入的上下文
     */
    public static void initial(ServletContext newSct, ApplicationContext newCtx) {
        ctx = newCtx;
        sct = newSct;
        LOGGER.info("SpringUtil initial successful!");
    }

    /**
     * 根据名称和类型获取Bean实例
     *
     * @param clazz Bean类
     * @param <T>   指定类型
     * @return Bean实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T getServiceBean(Class<T> clazz) {
        if (ctx == null) {
            LOGGER.warn("SpringUtil has not been initialed!");
            return null;
        }
        return (T) ctx.getBean(clazz);
    }

    /**
     * 获取应用上下文
     */
    public static ApplicationContext getCtx() {
        return ctx;
    }

    /**
     * 获取Servlet上下文
     */
    public static ServletContext getSct() {
        return sct;
    }
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐