【发布时间】:2015-01-07 00:55:20
【问题描述】:
我坚持从纯 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 @see #load() 方法并找到“return create(cd, false);”
更新 2
我在 Spring 文档中发现了一个非常有趣的东西,叫做“查找方法注入”: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-lookup-method-injection
还有一张有趣的 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
更新 4
所有这些“查找”方法的问题是它们不支持传递任何参数。我还需要传递参数,就像我对 applicationContext.getBean("runtimeBean", arg1, arg2) 所做的那样。看起来它在某个时候被https://jira.spring.io/browse/SPR-7431修复了
更新 5
Google Guice 有一个名为 AssistedInject 的简洁功能。 https://github.com/google/guice/wiki/AssistedInject
【问题讨论】:
-
如果您使用 new 运算符和构造函数实例化对象,则它不是 Spring Bean,因此不符合 DI 条件。
-
您能详细解释一下您想做什么吗?
-
@KevinBowersox 如果对象通过正确拦截的
@Bean方法返回,则不正确,例如在配置类上。不过,这听起来很像 XY 问题,而像 Spring Cloud Connectors 这样的东西可能是更好的选择。 -
@chrylis 同意,Java 配置需要 new 运算符。我更多地指的是
Container类及其对new的使用。这不会与 Spring 一起飞行。 -
你们说得对,我的问题是如何重新设计代码以使其工作。我想做什么?我想以某种方式重新设计代码以在配置中定义运行时 bean(但是如果我什至不知道 bean 的编号和属性怎么办),或者拥有某种可以在运行时创建 bean 并执行完整 spring 的工厂编织...其实我不知道,我需要有人解释如何正确地做事。
标签: java spring dependency-injection refactoring guice