Java 以编程方式检索Bean

Java 以编程方式检索Bean,java,spring,javabeans,Java,Spring,Javabeans,我有这个带有@Configuration-Spring注释的MyConfig对象。 我的问题是如何以编程方式(在常规类中)检索bean 例如,代码片段如下所示。 提前谢谢 @Configuration public class MyConfig { @Bean(name = "myObj") public MyObj getMyObj() { return new MyObj(); } } 如果您真的需要从ApplicationContext获取bean

我有这个带有@Configuration-Spring注释的MyConfig对象。 我的问题是如何以编程方式(在常规类中)检索bean

例如,代码片段如下所示。 提前谢谢

@Configuration
public class MyConfig {
    @Bean(name = "myObj")
    public MyObj getMyObj() {
        return new MyObj();
    }
}
如果您真的需要从
ApplicationContext
获取bean,最简单(尽管不是最干净)的方法是让您的类实现
ApplicationContextAware
接口并提供
setApplicationContext()
方法

一旦您有了对
ApplicationContext
的引用,您就可以访问许多将向您返回bean实例的方法

缺点是,这会使您的类了解Spring上下文,除非必要,否则应该避免使用Spring上下文

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

public class Var {
    public void varMethod(){
            Foo foo = new Foo();
    }
}
但是,您很少需要直接访问ApplicationContext。通常只启动一次,让bean自动填充自己

给你:

public class MyFancyBean implements ApplicationContextAware {

  private ApplicationContext applicationContext;

  void setApplicationContext(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }

  public void businessMethod() {
    //use applicationContext somehow
  }

}
请注意,您不必提及applicationContext.xml中已经包含的文件。现在,您只需按名称或类型获取一个bean:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
请注意,启动Spring有很多方法—使用ContextLoaderListener、@Configuration class等。

尝试以下方法:

ctx.getBean("someName")

请尝试
@Autowire
ing。。。或者更准确地说,
@Qualifier(“myObj”)
。我不能执行@Autowire,因为我必须在运行时中使用new创建Foo对象。请检查。相关:。检查我答案底部的部分。你在Spring上下文文件中设置了吗?@Xstian我也通过
ApplicationContext
进行设置;D
public class Foo {
    public Foo(ApplicationContext context){
        context.getBean("myObj")
    }
}

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