问题描述
@Configuration
public class MyConfig {
@Bean(name = "myObj")
public MyObj getMyObj() {
return new MyObj();
}
}
我有一个带有@Configuration Spring批注的MyConfig对象.我的问题是,如何才能以编程方式(在常规类中)检索Bean?
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();
}
}
推荐答案
此处是示例
public class MyFancyBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void businessMethod() {
//use applicationContext somehow
}
}
但是,您几乎不需要直接访问ApplicationContext.通常,您只需启动一次,然后让Bean自动填充自己.
However you rarely need to access ApplicationContext directly. Typically you start it once and let beans populate themselves automatically.
您在这里:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
请注意,您不必提及applicationContext.xml中已经包含的文件.现在,您只需按名称或类型获取一个bean:
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")
请注意,有很多启动Spring的方法-使用ContextLoaderListener,@ Configuration类等.
Note that there are tons of ways to start Spring - using ContextLoaderListener, @Configuration class, etc.
这篇关于以编程方式检索Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!