如何在运行时实例化 Spring 管理的 bean?

新手上路,请多包涵

我坚持从普通 Java 到 Spring 的简单重构。应用程序有一个“容器”对象,它在运行时实例化它的部分。让我用代码解释一下:

 public class Container {
    private List<RuntimeBean> runtimeBeans = new ArrayList<RuntimeBean>();

    public void load() {
        // repeated several times depending on external data/environment
        RuntimeBean beanRuntime = createRuntimeBean();
        runtimeBeans.add(beanRuntime);
    }

    public RuntimeBean createRuntimeBean() {
         // should create bean which internally can have some
         // spring annotations or in other words
         // should be managed by spring
    }
}

基本上,在加载容器期间,容器会要求一些外部系统向他提供有关每个 RuntimeBean 的数量和配置的信息,然后根据给定的规范创建 bean。

问题是:通常我们在 Spring 做的时候

ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
Container container = (Container) context.getBean("container");

我们的对象已完全配置并注入了所有依赖项。但在我的例子中,我必须在执行 load() 方法后实例化一些也需要依赖注入的对象。

我怎样才能做到这一点?

我正在使用基于 Java 的配置。我已经尝试为 RuntimeBeans 建立工厂:

 public class BeanRuntimeFactory {

    @Bean
    public RuntimeBean createRuntimeBean() {
        return new RuntimeBean();
    }
}

期望 @Bean 在所谓的“精简”模式下工作。 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html 不幸的是,我发现简单地做 new RuntimeBean(); 没有区别;这是一篇有类似问题的帖子: How to get beans created by FactoryBean spring managed?

还有 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Configurable.html 但在我的例子中它看起来像一把锤子。

我还尝试了 ApplicationContext.getBean(“runtimeBean”, args) ,其中 runtimeBean 具有“原型”范围,但 getBean 是一个糟糕的解决方案。


更新 1

更具体地说,我正在尝试重构此类: https ://github.com/apache/lucene-solr/blob/trunk/solr/core/src/java/org/apache/solr/core/CoreContainer.java @查看 #load() 方法并找到“return create(cd, false);”

更新 2

我在 spring 文档中发现了名为“查找方法注入”的非常有趣的东西:http: //docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-lookup-method -注射

还有一个有趣的 jira 票 https://jira.spring.io/browse/SPR-5192 Phil Webb 说 https://jira.spring.io/browse/SPR-5192?focusedCommentId=86051&page=com.atlassian.jira .plugin.system.issuetabpanels:comment-tabpanel#comment-86051 应该在这里使用 javax.inject.Provider(这让我想起了 Guice)。

更新 3

还有 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.html

更新 4

所有这些“查找”方法的问题是它们不支持传递任何参数。我还需要传递参数,就像我对 applicationContext.getBean(“runtimeBean”, arg1, arg2) 所做的那样。看起来它在某个时候被 https://jira.spring.io/browse/SPR-7431 修复了

更新 5

Google Guice 有一个名为 AssistedInject 的巧妙功能。 https://github.com/google/guice/wiki/AssistedInject

原文由 Vadim Kirilchuk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 634
2 个回答

看起来我找到了解决方案。由于我使用的是基于 Java 的配置,因此它比您想象的还要简单。 xml 中的替代方法是查找方法,但仅限于 spring 版本 4.1.X,因为它支持将参数传递给该方法。

这是一个完整的工作示例:

 public class Container {
    private List<RuntimeBean> runtimeBeans = new ArrayList<RuntimeBean>();
    private RuntimeBeanFactory runtimeBeanFactory;

    public void load() {
        // repeated several times depending on external data/environment
        runtimeBeans.add(createRuntimeBean("Some external info1"));
        runtimeBeans.add(createRuntimeBean("Some external info2"));
    }

    public RuntimeBean createRuntimeBean(String info) {
         // should create bean which internally can have some
         // spring annotations or in other words
         // should be managed by spring
         return runtimeBeanFactory.createRuntimeBean(info);
    }

    public void setRuntimeBeanFactory(RuntimeBeanFactory runtimeBeanFactory) {
        this.runtimeBeanFactory = runtimeBeanFactory;
    }
}

public interface RuntimeBeanFactory {
    RuntimeBean createRuntimeBean(String info);
}

//and finally
@Configuration
public class ApplicationConfiguration {

    @Bean
    Container container() {
        Container container = new Container(beanToInject());
        container.setBeanRuntimeFactory(runtimeBeanFactory());
        return container;
    }

    // LOOK HOW IT IS SIMPLE IN THE JAVA CONFIGURATION
    @Bean
    public BeanRuntimeFactory runtimeBeanFactory() {
        return new BeanRuntimeFactory() {
            public RuntimeBean createRuntimeBean(String beanName) {
                return runtimeBean(beanName);
            }
        };
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    RuntimeBean runtimeBean(String beanName) {
        return new RuntimeBean(beanName);
    }
}

class RuntimeBean {
    @Autowired
    Container container;
}

而已。

感谢大家。

原文由 Vadim Kirilchuk 发布,翻译遵循 CC BY-SA 4.0 许可协议

我认为你的概念是错误的

RuntimeBean beanRuntime = createRuntimeBean();

您正在绕过 Spring 容器并诉诸于使用常规 java 构造函数,因此工厂方法上的任何注释都将被忽略,并且此 bean 永远不会由 Spring 管理

这是在一种方法中创建多个原型 bean 的解决方案,虽然看起来不漂亮但应该可以工作,我在 RuntimeBean 中自动装配容器作为日志中显示的自动装配的证明,您还可以在日志中看到当您运行它时每个 bean 都是原型的新实例.

 @Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        Container container = (Container) context.getBean("container");
        container.load();
    }
}

@Component
class Container {
    private List<RuntimeBean> runtimeBeans = new ArrayList<RuntimeBean>();
    @Autowired
    ApplicationContext context;

    @Autowired
    private ObjectFactory<RuntimeBean> myBeanFactory;

    public void load() {

        // repeated several times depending on external data/environment
        for (int i = 0; i < 10; i++) {
            // **************************************
            // COMENTED OUT THE WRONG STUFFF
            // RuntimeBean beanRuntime = context.getBean(RuntimeBean.class);
            // createRuntimeBean();
            //
            // **************************************

            RuntimeBean beanRuntime = myBeanFactory.getObject();
            runtimeBeans.add(beanRuntime);
            System.out.println(beanRuntime + "  " + beanRuntime.container);
        }
    }

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public RuntimeBean createRuntimeBean() {
        return new RuntimeBean();
    }
}

// @Component

class RuntimeBean {
    @Autowired
    Container container;

} '

原文由 mariubog 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题