0

I have had chance of working on only one project using spring , and the way it worked was

  1. Make a singleton class (lets say MySpringHelper), that has method like getBean(String beanName)
  2. What getBean(String) does is, it first checks existence of applicationContext, if it exists uses same to get the bean , else creates new applicationContext and returns the bean
  3. Wherever in you project you need a bean simply call MySpringHelper.getBean("abc")

Keeping this in mind , when i was studying spring , i noticed interface "ApplicationContextAware" ... I am not sure when will this be needed, uses above pattern such interface seems not of any use. Or the above Singleton MySpringHelper pattern/approach is incorrect ??

Looking forward to learn from your experience

To give more details on application , its like a pdf file generator, 1 pdf file having 12-15 different charts, so the main method runs 1 thread for each chart , and inside these chart logic we are using singleton MySpringHelper

Lav
  • 1,283
  • 5
  • 21
  • 48
  • 2
    Why do app context work manually when you can do it automatically? – Dave Newton Oct 10 '14 at 11:52
  • 1
    Doesn't your stringly-typed solution require casting? Maybe you could at least do something like `MySpringHelper.getBean(ABC.class)`? Or use Spring's autowiring capabilities... – Anna Zubenko Oct 10 '14 at 12:49

1 Answers1

1

Why are you checking the existance of applicationContext? It should be there if your helper bean is configured in xml and has setter method in it. There is no need to create application context in that case.

For your case, I would suggest you get applicationContext injected by Spring rather than by using ApplicationContextAware.

SMA
  • 36,381
  • 8
  • 49
  • 73
  • added project description in ques, its like a multi threaded project, so one doesnt know which thread will start first and initializes the appContext ... guessing hence the check .... – Lav Oct 10 '14 at 12:30
  • so why don't you just inject applicationContext and leave it with spring to inject it? – SMA Oct 10 '14 at 12:37
  • 1
    @Lav, you could first start application context, make sure it's loaded (via `org.springframework.context.ApplicationListener `), and then start processing charts? – Anna Zubenko Oct 10 '14 at 12:53