不需要有多个应用程序上下文。在许多情况下,我们需要一个共享的应用程序上下文。
为了避免在应用程序中创建多个应用程序上下文,请执行以下操作。
当 applicationcontextprovider bean 被创建时,spring 框架会将 ApplicationContext 注入到 setApplicationContext 中。
现在我们有了一个静态实用程序方法 getApplicationContext,它会在需要时返回应用程序上下文。
每当您需要应用程序上下文时,您只需说:ApplicationContextProvider.getApplicationContext(); ,这将返回共享的应用程序上下文。
/* 应用上下文提供者类 */
public class ApplicationContextProvider implements ApplicationContextAware {
    private static Logger logger = Logger.getLogger(ApplicationContextProvider.class);
    private static ApplicationContext ctx;
    @Override
    public void setApplicationContext(ApplicationContext arg0)
            throws BeansException {
        if (arg0 != null) {
            ctx=arg0;
        }
    }
    public synchronized static ApplicationContext getApplicationContext(){
        if (ctx==null) {
            logger.info("Getting the context again as it is null");
            ctx = new ClassPathXmlApplicationContext("Spring-All-Module.xml");
        }
        return ctx;
    }
}
弹簧 XML:
<bean id="applicationContextProvider" class="dell.harmony.service.ApplicationContextProvider"></bean> 
从您的主程序类:
try {
            logger.info("Spring Application Context !!");
            ApplicationContext context = new ClassPathXmlApplicationContext(
                    "/Spring-All-Module.xml");
            logger.info("Spring Application Context - End !!");
        } catch (Exception e) {
                    logger.error("Exception in getting the Spring Application Context !!");
                     /* log the exception */
        }
每当您需要上下文时,您只需说://获取应用程序上下文
ApplicationContext 上下文 = ApplicationContextProvider.getApplicationContext(); 
dl = (SingleDataLoader) context.getBean("singledataloaderdao");