Spring:使用构建器模式创建 bean [英] Spring: Using builder pattern to create a bean
本文介绍了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屋!
查看全文