>我有实用程序方法,它将字符串作为输入参数,并给我一个与输入相对应的对象。我需要从 Spring 引导请求映射方法调用此实用程序方法。
现在我的问题是以下两种方法的优缺点是什么?
- 将实用工具方法设为静态并调用它。
- 将方法制作为原型 bean 并调用 bean。
方法 1 的示例代码:
**//SourceSystem can change at runtime**
public static FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
方法 2 的示例代码:
@Bean
@Scope(value = "prototype")
**//SourceSystem can change at runtime**
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
PS :从其他帖子收集的样本。
如果你已经在使用 Spring,那么选择单例(每个 Spring 容器实例一个 bean 对象(bean(这是默认范围(,如果你的静态方法没有任何共享状态,这是可以的。如果选择原型,则 Spring 容器将为每个getBean()
调用返回 bean 对象的新实例。并将该 bean 注入到需要调用该方法的对象中。此方法也比静态方法对单元测试更友好,因为您可以在测试应用程序上下文中提供使用此方法的 Bean 测试实现。如果是静态 methid,您将需要 PowerMock 或其他第三方库来模拟 stick 方法以进行单元测试。
更新
在您的情况下,应该有新的豆子
@Service
public MyReportBeanFactory {
@Autowired
private Dao dao;
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
}
然后你需要把这个工厂 bean 注入到你想要调用fixedLengthReport()
的类中