代码之家  ›  专栏  ›  技术社区  ›  Sanchay vincent

如何一次性初始化SpringContext并在任务间共享?

  •  2
  • Sanchay vincent  · 技术社区  · 8 年前

    我试图在我的Spark应用程序中初始化spring上下文。我想要从节点中的上下文以及重用bean。以下是相同的代码:-

    shipperRD2.foreach(shipper->{
    
     AmazonS3 amazonS3Client = AmazonS3ClientBuilder.standard().build();
                        FileSystemXmlApplicationContext context2 = new FileSystemXmlApplicationContext("https://s3.console.aws.amazon.com/s3/object/spring-configuration/app-context.xml");
    
    PersistenceWrapper persistenceWrapper = context.getBean(PersistenceWrapper.class);
    });
    

    然而,这导致每次在从属节点上运行新任务时都会刷新上下文。有什么方法可以避免这种行为吗。基本上,只需在第一次运行任务时初始化上下文,并在后续任务中重新使用该上下文。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Sanchay vincent    8 年前

    正如Jacek所提到的,我尝试了单例模式,它成功了。

    public class SpringInit {
    
        private static FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(fileName);
    
        private SpringInit(){
        }
    
        public static FileSystemXmlApplicationContext getInstance(){
            return context;
        }
     }
    

    从火花中,

    shipperRD2.foreach(shipper->{
    
      FileSystemXmlApplicationContext context = SpringInit.getInstance();
    PersistenceWrapper persistenceWrapper = context.getBean(PersistenceWrapper.class);
    });