Spring:使用构建器模式创建一个bean [英] Spring: Using builder pattern to create a bean

查看:128
本文介绍了Spring:使用构建器模式创建一个bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ektorp 连接到CouchDB。

I use ektorp to connect to CouchDB.

构建ektorp HttpClient 实例的方法是使用构建器模式:

The way to build an ektorp HttpClient instance is to use builder pattern:

HttpClient httpClient = new StdHttpClient.Builder()
                                .host("mychouchdbhost")
                                .port(4455)
                                .build();

我对Spring来说比较新。请教我如何在我的上下文中配置 HttpClient ,以便通过 Builder 创建它。

I am relatively new to Spring. Please advice me on how I can configure an HttpClient in my context to create it via the Builder.

一种方法是使用 @Configuration 。有没有其他选择?

One way to do this is with @Configuration. Are any other options?

推荐答案

您可以尝试实现 FactoryBean

public class HttpFactoryBean implements FactoryBean<HttpClient>{

private String host;
private int port;


public HttpClient getObject() throws Exception {
    return new StdHttpClient.Builder()
                            .host(host)
                            .port(port)
                            .build();
}

public Class<? extends HttpClient> getObjectType() {
    return StdHttpClient.class;
}

public boolean isSingleton() {
    return true;
}

public void setHost(String host) {
    this.host = host;
}

public void setPort(int port) {
    this.port = port;
}}

并添加到配置以下bean定义:

And add to config following bean definition:

<beans ..."> 
   <bean name="myHttpClient" class="HttpFactoryBean">
       <property name="port" value="8080"/>
       <property name="host" value="localhost"/>
   </bean>
</beans>

然后你可以将这个bean注入另一个bean,它将被解析为 StdHttpClient 实例。

Then you can inject this bean to another beans, it will be resolved as StdHttpClient instance.

这篇关于Spring:使用构建器模式创建一个bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆