@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();
}
}
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.
@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.
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.
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With