retrieve Bean programmatically

user800799 picture user800799 · Sep 11, 2014 · Viewed 47.7k times · Source
@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();
    }
}

Answer

Grim picture Grim · Sep 11, 2014

Try this:

public class Foo {
    public Foo(ApplicationContext context){
        context.getBean("myObj")
    }
}

public class Var {
    @Autowired
    ApplicationContext context;
    public void varMethod(){
            Foo foo = new Foo(context);
    }
}