Java 我想要Spring注入的函数采用varargs。我应该提供一个重载来代替列表吗?
我有一个工厂方法来包装一些订单相关的东西:Java 我想要Spring注入的函数采用varargs。我应该提供一个重载来代替列表吗?,java,xml,spring,spring-mvc,dependency-injection,Java,Xml,Spring,Spring Mvc,Dependency Injection,我有一个工厂方法来包装一些订单相关的东西: import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; public class ThingBoxProcessor { public static ThingBox forInputThings(Thing... thingsToProcess) { ThingBox thingBox = new Thing
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class ThingBoxProcessor {
public static ThingBox forInputThings(Thing... thingsToProcess) {
ThingBox thingBox = new ThingBox();
for (Thing thing : Lists.reverse(ImmutableList.copyOf(thingsToProcess))) {
thingBox.store(thing);
}
return thingBox;
}
}
我是这样注射的:
<bean name="Things" class="ThingBoxProcessor" factory-method="forInputThings">
<constructor-arg>
<list>
<ref bean="ThingTwo" />
<ref bean="ThingOne" />
<!-- imagine a couple dozen other things that do different order-sensitive things -->
</list>
</constructor-arg>
</bean>
Spring是否正在创建ArrayList,然后将其转换为数组?提供过载是否有任何显著的性能优势,例如:
public static ThingBox forInputThings(Thing... thingsToProcess) {
return forInputThings(ImmutableList.copyOf(thingsToProcess));
}
public static ThingBox forInputThings(List<Thing> thingsToProcess) {
ThingBox thingBox = new ThingBox();
for (Thing thing : Lists.reverse(thingsToProcess)) {
thingBox.store(thing);
}
return thingBox;
}
用于输入内容的公共静态ThingBox(Thing…ThingStopProcess){
返回输入(不可变列表.copyOf(ThingStopProcess));
}
用于输入的公共静态ThingBox(列表ThingStopProcess){
ThingBox ThingBox=新ThingBox();
for(Thing:list.reverse(thingsToProcess)){
储物箱;储物(物);
}
返回物箱;
}
(这不是我感兴趣的。我知道我可以将spring xml列表注入到varargs参数中;我只想知道是否有性能原因需要这样做。)我不会花任何时间来解决这个问题,因为: 假设您正在处理单例范围的Springbean,此操作只会发生一次。 另外:启动Spring上下文至少需要几秒钟的时间,因为它需要读取配置文件、加载类等。相比之下,在数组和任何合理大小的列表之间来回转换的代价(从某种意义上讲,在Spring中输入的参数可能不会超过50°),可能会使您的启动速度增加大约0000001%
因此,从可靠性、可维护性或类似的角度来看,考虑您应该选择哪个选项是有意义的,但从性能角度看,它实际上是无关紧要的。在我的测试中,Spring选择了采用列表的版本,而不是采用varargs的版本。我个人倾向于选择一个更干净、更容易混淆的API(即只有一个函数),并且只在分析发现问题时担心性能;第二种方法显然避免了创建不可变的副本,该副本随后会立即被丢弃。