-2

How can I get existing singleton instance of a bean from Spring Container. I do not want to load the config again as follow but want to retrieve the bean created already using this config;

ApplicationContext context =  new ClassPathXmlApplicationContext("some.xml");

Thanks in advance for early attention.

A4L
  • 17,353
  • 6
  • 49
  • 70
Kash
  • 1
  • 3
  • And ... did you try to read the doc or just type `spring tutorial` in google ? – Serge Ballesta Oct 02 '14 at 09:15
  • Look [here](http://stackoverflow.com/questions/129207/getting-spring-application-context) maybe this helps. – Jens Oct 02 '14 at 09:16
  • If your bean is declared/annotated to be singleton - which ist the default [scope](http://www.tutorialspoint.com/spring/spring_bean_scopes.htm) - then getting it from your BeanFactory/Context using its id should be enough. – A4L Oct 02 '14 at 09:16
  • yes but not found suitable answer. – Kash Oct 02 '14 at 09:19
  • That is way there is a little thing called dependency injection. – M. Deinum Oct 02 '14 at 09:54

1 Answers1

1

Here an Example

public class MyFancyBean implements ApplicationContextAware {

  private ApplicationContext applicationContext;

  void setApplicationContext(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }

  public void businessMethod() {
    //use applicationContext somehow
  }

}

Here you go:

applicationContext.getBean("someName")

Note that there are tons of ways to start Spring - using ContextLoaderListener, @Configuration class, etc.

Xstian
  • 8,184
  • 10
  • 42
  • 72