首页 > 解决方案 > 静态方法与原型 bean

问题描述

我有实用方法,它将字符串作为输入参数并给我一个与输入相对应的对象。我需要从 Spring 引导请求映射方法中调用此实用程序方法。

现在我的问题是以下两种方法的优缺点是什么?

  1. 将实用程序方法设为静态并调用它。
  2. 将方法制作为原型 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:从其他帖子收集的样本。

标签: javaspringspring-bootstatic-methodsspring-bean

解决方案


如果您已经使用 Spring,则选择单例(每个 Spring 容器实例一个 bean 对象)bean(这是默认范围),如果您的静态方法没有任何共享状态,则可以。如果您选择原型,那么 Spring 容器将为每次getBean()调用返回 bean 对象的新实例。并将该 bean 注入需要调用该方法的对象。这种方法也比静态方法对单元测试更友好,因为您可以在测试应用程序上下文中使用这种方法提供 bean 的测试实现。在静态方法的情况下,您将需要 PowerMock 或其他 3rd 方库来模拟棒方法以进行单元测试。

更新

在你的情况下应该有新豆

@Service
public MyReportBeanFactory {

   @Autowired
   private Dao dao;

   public FixedLengthReport fixedLengthReport(String sourceSystem) {
      return new TdctFixedLengthReport(sourceSystem, dao);
   }
}

然后您需要将此工厂 bean 注入您要调用的类中fixedLengthReport()


推荐阅读