【问题标题】:Injecting an object that uses builder pattern inside spring constructor在spring构造函数中注入一个使用构建器模式的对象
【发布时间】:2020-03-24 17:45:22
【问题描述】:

我在这里看到了很多人问这个问题,但没有一个答案对我的情况有帮助。

我正在使用square sdk,它提示我在使用之前创建这样的客户端。

import com.squareup.square.SquareClient;
import com.squareup.square.Environment;

SquareClient square = new SquareClient.Builder()
    .environment(Environment.SANDBOX)
    .accessToken("YOUR_SANDBOX_ACCESS_TOKEN")
    .build();

鉴于服务看起来像这样,spring 将无法找到所需的 bean。并会给出一个错误,例如,

没有“squareClient”类型的限定bean

所以我的问题是如何加载这两个参数到服务中使用依赖注入以使方形服务可测试。

@Service
public class SquareService {
    private final SquareClient squareClient;

    public SquareService(SquareClient squareClient) {
        this.squareClient = squareClient;
    }
}

我的测试我有

@Before
public void setup() {
    sut = new SquareService(new SquareClient.Builder()
    .environment(Environment.SANDBOX)
    .accessToken("YOUR_SANDBOX_ACCESS_TOKEN")
    .build());
}

【问题讨论】:

    标签: java spring square-connect square


    【解决方案1】:

    您可以创建一个@Configuration 类并手动创建bean:

    @Configuration
    public class SquareConfiguration {
    
      @Value("${my.config.sandboxAccessToken}")
      private String sandboxAccessToken;
    
      @Bean
      public SquareService createSquareService(){
        return new SquareService(new SquareClient.Builder()
          .environment(Environment.SANDBOX)
          .accessToken(this.sandboxAccessToken)
          .build());
      }
    }
    

    【讨论】:

    • 如果我将其他依赖项传递给构造函数,我现在还必须在 SquareConfiguration 类中进行设置吗?
    • 您可以将这些参数(如果它们本身是 bean)传递给 @bean-method:public SquareService createSquareService(MyComponent myComponent)...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2017-08-01
    • 2015-09-04
    • 1970-01-01
    相关资源
    最近更新 更多