简体   繁体   中英

Accessing cached ApplicationContext in spring

I need to fetch a singleton bean from same ApplicationContext twice in 2 different classes.

Example snippet :

CLass A {
  public void foo(){
    ApplicationContext context = new ClassPathXmlApplicationContext("common.spring.xml");
    MyParametrizedSingletonClass myParametrizedSingletonClass = (MyParametrizedSingletonClass) context.getBean("myParametrizedSingletonClass");
    // do more stuff..
  }
CLass B {
  public void bar(){
    ApplicationContext context = new ClassPathXmlApplicationContext("common.spring.xml");
    MyParametrizedSingletonClass myParametrizedSingletonClass = (MyParametrizedSingletonClass) context.getBean("myParametrizedSingletonClass");
    // do more stuff..
  }

Since MyParametrizedSingletonClass is a singletom it if its constructor is called more than once for same constructor arguments it throws error.

How do I cache and reuse ApplicationContext with spring?

You are creating two different context, so even if bean is singleton it will create single instance per context,

if you want to cache application context you can create a class and provide singleton instance of application context

Autowire the bean.

By default the spring injects the autowired beans into required classes and these beans are not created an new everytime. They are singleton by default.

在bean名称myParametrizedSingletonClass的common.spring.xml文件中,在xml文件中定义bean的同时,将范围单例作为参数添加到其中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM