Spring--spring管理BEANを手動で呼び出す

5447 ワード

開発中、springによって管理されていないメソッドがspringによって管理されているメソッドを呼び出したい場合、次のコードのようにメソッドを呼び出すと、空のポインタの異常が発生します.
    @Autowired
    private HfPaymentService hfPaymentService;

次は、springによって管理されているbeanを手動で呼び出すツールクラスです.
package com.redhorse.util;

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.stereotype.Service;

/** *        Spring ApplicationContext,                  ApplicaitonContext. */
@Service
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("  ApplicationContext SpringContextHolder:" + applicationContext);

        if (SpringContextHolder.applicationContext != null) {
            logger.warn("SpringContextHolder  ApplicationContext   ,   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);
    }

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

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

使用方法:
RepaymentService repaymentService = (RepaymentService) SpringContextHolder.getBean("repaymentService");