以编程方式检索Bean

时间:2014-09-10 22:08:48

标签: java spring javabeans

@Configuration
public class MyConfig {
    @Bean(name = "myObj")
    public MyObj getMyObj() {
        return new MyObj();
    }
}

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

例如,代码段看起来像这样。 提前谢谢。

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

public class Var {
    public void varMethod(){
            Foo foo = new Foo();
    }
}

3 个答案:

答案 0 :(得分:8)

这是一个例子

public class MyFancyBean implements ApplicationContextAware {

  private ApplicationContext applicationContext;

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

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

}

但是,您很少需要直接访问ApplicationContext。通常,您启动一​​次,让bean自动填充。

你走了:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

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

ctx.getBean("someName")

请注意,有很多方法可以启动Spring - 使用ContextLoaderListener,@ Configuration类等。

答案 1 :(得分:7)

试试这个:

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

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

答案 2 :(得分:3)

如果您真的需要从ApplicationContext获取bean,那么最简单(尽管不是最干净)的方法是让您的类实现ApplicationContextAware接口并提供setApplicationContext()方法。

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

缺点是这使得你的班级知道Spring语境,除非必要,否则应该避免。

相关问题