com.rosy.bill.utils.spring.SpringContextHolder.java Source code

Java tutorial

Introduction

Here is the source code for com.rosy.bill.utils.spring.SpringContextHolder.java

Source

/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: SpringContextHolder.java,v 1.1 2011/03/28 08:01:23 zwm Exp $
 */
package com.rosy.bill.utils.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

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

    private static ApplicationContext applicationContext = null;

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

    /**
     * ApplicationContextAware?, Context????.
     */
    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.clear();
    }

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

    /**
     * ????applicationContext?Bean, .
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

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

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

    /**
     * ApplicationContext?.
     */
    private static void assertContextInjected() {
        if (applicationContext == null) {
            throw new IllegalStateException(
                    "applicaitonContext,applicationContext.xmlSpringContextHolder");
        }
    }
}