Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 376
user800799 Avatar asked Sep 10 '14 22:09

user800799


People also ask

What is @bean annotation used for?

Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.

Can we use @bean without @configuration?

@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.

How do you get beans from Spring containers?

Ways to get loaded beans in Spring / Spring boot ApplicationContext. getBeanDefinitionNames() will return names of beans which is correctly loaded. getBean(String name) method using that we can get particular bean using bean name.


2 Answers

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);
    }
}
like image 153
Grim Avatar answered Oct 04 '22 23:10

Grim


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.

like image 40
Xstian Avatar answered Oct 04 '22 23:10

Xstian