【问题标题】:Static method vs prototype bean静态方法与原型 bean
【发布时间】:2018-09-09 09:54:44
【问题描述】:

我有一个实用方法,它将字符串作为输入参数并给我一个与输入对应的对象。我需要从 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:从其他帖子收集的样本。

【问题讨论】:

    标签: java spring spring-boot static-methods spring-bean


    【解决方案1】:

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

    更新

    在你的情况下应该有新的 bean

    @Service
    public MyReportBeanFactory {
    
       @Autowired
       private Dao dao;
    
       public FixedLengthReport fixedLengthReport(String sourceSystem) {
          return new TdctFixedLengthReport(sourceSystem, dao);
       }
    }
    

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

    【讨论】:

    • 默认作用域是singleton(单例作用域是Spring中的默认作用域)
    • 我不能使用单例作为 bean 更改的输入参数,返回类型将基于输入参数,添加了有问题的示例实用程序方法。
    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 2012-07-14
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多