以编程方式检索Bean

use*_*799 15 java spring javabeans

@Configuration
public class MyConfig {
    @Bean(name = "myObj")
    public MyObj getMyObj() {
        return new MyObj();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

public class Var {
    public void varMethod(){
            Foo foo = new Foo();
    }
}
Run Code Online (Sandbox Code Playgroud)

Xst*_*ian 8

这是一个例子

public class MyFancyBean implements ApplicationContextAware {

  private ApplicationContext applicationContext;

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

干得好:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Run Code Online (Sandbox Code Playgroud)

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

ctx.getBean("someName")
Run Code Online (Sandbox Code Playgroud)

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


Pet*_*der 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Jim*_*son 5

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

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

缺点是,这使您的类意识到Spring上下文,除非有必要,否则应避免使用该上下文。