【问题标题】:retrieve Bean programmatically以编程方式检索 Bean
【发布时间】:2014-11-04 17:17:17
【问题描述】:
@Configuration
public class MyConfig {
    @Bean(name = "myObj")
    public MyObj getMyObj() {
        return new MyObj();
    }
}

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

例如,代码 sn-p 看起来像这样。 提前致谢。

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

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

【问题讨论】:

标签: java spring javabeans


【解决方案1】:

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

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

缺点是这会让你的类知道 Spring 上下文,除非必要,否则应该避免。

【讨论】:

    【解决方案2】:

    这里是一个例子

    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 类等。

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

      • @Xstian 我也通过ApplicationContext 去。 ;D
      猜你喜欢
      • 2013-08-11
      • 1970-01-01
      • 2012-01-30
      • 2014-02-07
      • 2010-11-04
      • 2018-07-21
      • 2011-04-07
      • 2011-03-26
      • 1970-01-01
      相关资源
      最近更新 更多