com.levilee.levipetstore.orm.util.SpringContextHolder.java Source code

Java tutorial

Introduction

Here is the source code for com.levilee.levipetstore.orm.util.SpringContextHolder.java

Source

package com.levilee.levipetstore.orm.util;
/**
 * Copyright (c) 2005-2012 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring ApplicationContext, ApplicaitonContext.
 * 
 * @author calvin
 */
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "applicationContext.xml");

    private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

    /**
     * ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * applicationContextBean, .
     */
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    /**
     * applicationContextBean, .
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * SpringContextHolderApplicationContextNull.
     */
    public static void clearHolder() {
        logger.debug("SpringContextHolderApplicationContext:" + applicationContext);
        applicationContext = null;
    }

    /**
     * ApplicationContextAware, Context.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        logger.debug("ApplicationContextSpringContextHolder:{}", applicationContext);

        if (SpringContextHolder.applicationContext != null) {
            logger.warn("SpringContextHolderApplicationContext, ApplicationContext:"
                    + SpringContextHolder.applicationContext);
        }

        SpringContextHolder.applicationContext = applicationContext; //NOSONAR
    }

    /**
     * DisposableBean, Context.
     */
    @Override
    public void destroy() throws Exception {
        SpringContextHolder.clearHolder();
    }

    /**
     * ApplicationContext.
     */
    private static void assertContextInjected() {
        Validate.validState(applicationContext != null,
                "applicaitonContext, applicationContext.xmlSpringContextHolder.");
    }
}