如何获得由FactoryBean spring创建的bean? [英] How to get beans created by FactoryBean spring managed?

查看:137
本文介绍了如何获得由FactoryBean spring创建的bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FactoryBean 可用于以编程方式创建可能需要复杂实例化逻辑的对象。

The FactoryBean can be used to programmatically create objects which might require complex instantiation logic.

但是,似乎 FactoryBean 创建的 bean 不会变成春天管理。这种解释是否正确?如果是这样,有什么好的解决方法吗?包含一个简短的代码示例来说明我的问题。

However, it seems that the beans created by the FactoryBean doesn't become spring managed. Is this interpretation correct? If so, are there any nice workarounds? A short code sample is included to illustrate my problem.

ApplicationContext:

ApplicationContext:

<bean id="searcher" class="some.package.SearcherFactory" /> 
<bean id="service" class="some.package.Service" /> 

工厂实施:

public class SearcherFactory implements FactoryBean<Searcher> {

    @Override
    public Searcher getObject() throws Exception {
        return new Searcher(); // not so complex after all ;)
    }

    @Override
    public Class<Searcher> getObjectType() {
        return Searcher.class;
    }
    .... 
}

创建的类工厂:

public class Searcher() {
      private Service service;

      @Autowired
      public void setService(Service service) {
           // never invoked
           this.service=service;
      } 
}


推荐答案

FactoryBean 创建的对象由管理,但不由Spring实例化或配置。通过使用 FactoryBean ,您自己负责。所有注入和配置必须由 FactoryBean

The object created by the FactoryBean are managed by Spring, but not instantiated or configured by Spring. By using a FactoryBean, you take responsibility for that yourself. All injection and config must be handled by the FactoryBean

处理。有一种替代方案可能更适合您 - 使用基于注释的配置,而不是基于XML的配置。这意味着您可以在Java中使用复杂的实例化逻辑,同时仍然在对象本身上使用 @Autowired 之类的东西。

There is an alternative which may work better for you - use annotation-based config instead of XML-based config. This means you can have complex instantiation logic in Java, whilst still using things like @Autowired on the objects themselves.

我现在倾向于为所有非平凡的Spring应用程序使用注释样式配置,它使许多事情变得更容易。

I tend to use annotation-style config for all non-trivial Spring apps now, it makes many things a lot easier.

这篇关于如何获得由FactoryBean spring创建的bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆