Search code examples
javaspringjavabeans

retrieve Bean programmatically


@Configuration
public class MyConfig {
    @Bean(name = "myObj")
    public MyObj getMyObj() {
        return new MyObj();
    }
}

I have this MyConfig object with @Configuration Spring annotation. My question is that how I can retrieve the bean programmatically (in a regular class)?

for example, the code snippet looks like this. Thanks in advance.

public class Foo {
    public Foo(){
    // get MyObj bean here
    }
}

public class Var {
    public void varMethod(){
            Foo foo = new Foo();
    }
}

Solution

  • Here an Example

    public class MyFancyBean implements ApplicationContextAware {
    
      private ApplicationContext applicationContext;
    
      void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
      }
    
      public void businessMethod() {
        //use applicationContext somehow
      }
    
    }
    

    However you rarely need to access ApplicationContext directly. Typically you start it once and let beans populate themselves automatically.

    Here you go:

    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    

    Note that you don't have to mention files already included in applicationContext.xml. Now you can simply fetch one bean by name or type:

    ctx.getBean("someName")
    

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