2014-09-10 145 views
13
@Configuration 
public class MyConfig { 
    @Bean(name = "myObj") 
    public MyObj getMyObj() { 
     return new MyObj(); 
    } 
} 

我有@Configuration Spring批注的此MyConfig对象。 我的问题是,我怎样才能以编程方式检索bean(在普通类中)?例如,以编程方式检索Bean

代码片段看起来像这样。 在此先感谢。

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

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

尝试'@ Autowire'ing ...或更准确地说'@Qualifier(“myObj”)'。 – 2014-09-10 22:10:30

+0

我不能这样做@Autowire,因为我必须在运行时使用new创建Foo对象 – user800799 2014-09-10 22:11:29

+0

查看[Qualifier注释](http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference /html/beans.html#beans-autowired-annotation-qualifiers)。 – 2014-09-10 22:12:27

回答

6

这里为例

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中的文件。现在,你可以简单地通过名称或类型取一个绿豆:

ctx.getBean("someName") 

注意,有吨的方法来启动春 - 使用的ContextLoaderListener,@Configuration类等

2

最简单的(虽然不是最干净的)方法,如果你真的需要从ApplicationContext是让你的类实现ApplicationContextAware接口,并提供了setApplicationContext()方法来获取豆。

一旦您参考了ApplicationContext,就可以访问许多将向您返回bean实例的方法。

不足之处在于,这会让您的类意识到Spring上下文,除非必要,否则应避免这种情况。

5

试试这个:

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

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

@Xstian我也通过'ApplicationContext'去。 ; D – 2014-09-11 14:44:56

+0

你说得对,是类似的解决方案:D – Xstian 2014-09-11 15:03:11