1

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?

Nullpoet
  • 10,949
  • 20
  • 48
  • 65
  • Why are you constructing the application context yourself, why aren't you injecting the dependency into Classes `A` and `B`? IMHO those should be spring managed to. – M. Deinum Jun 18 '14 at 05:55

3 Answers3

2

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

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.

0

in common.spring.xml file for the bean name myParametrizedSingletonClass add the scope singleton to it as a parameter while defining the bean in the xml file

Anoop George
  • 742
  • 6
  • 6