spring可以通过的FactoryBean的形式把一个Factory整合到spring中。比如solr的客户端CommonsHttpSolrServer:
CommonsHttpSolrServer server = new CommonsHttpSolrServer("http://192.168.1.100:7100/solr/feed");
server.setSoTimeout(1000);
server.setConnectionTimeout(100);
server.setDefaultMaxConnectionsPerHost(100);
server.setMaxTotalConnections(100);
server.setAllowCompression(true);
server.setParser(new XMLResponseParser());
我模仿SqlMapClientFactoryBean的方式来实现一个solr的FactoryBean
public class SolrServerFactoryBean implements FactoryBean<CommonsHttpSolrServer>, InitializingBean {
private CommonsHttpSolrServer solrServer; // http://192.168.1.100:7100/solr/feed
private String solrServerUrl;
private int soTimeout; // socket read timeout
private int connectionTimeout;
private int defaultMaxConnectionsPerHost;
private int maxTotalConnections;
@Override
public void afterPropertiesSet() throws Exception {
solrServer = new CommonsHttpSolrServer(solrServerUrl);
solrServer.setAllowCompression(true);
solrServer.setSoTimeout(soTimeout);
solrServer.setConnectionTimeout(connectionTimeout);
solrServer.setDefaultMaxConnectionsPerHost(defaultMaxConnectionsPerHost);
solrServer.setMaxTotalConnections(maxTotalConnections);
}
@Override
public CommonsHttpSolrServer getObject() throws Exception {
return solrServer;
}
@Override
public Class<?> getObjectType() {
return (this.solrServer != null ? this.solrServer.getClass() : CommonsHttpSolrServer.class);
}
@Override
public boolean isSingleton() {
return true;
}
public void setSolrServerUrl(String solrServerUrl) {
this.solrServerUrl = solrServerUrl;
}
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public void setMaxTotalConnections(int maxTotalConnections) {
this.maxTotalConnections = maxTotalConnections;
}
public void setDefaultMaxConnectionsPerHost(int defaultMaxConnectionsPerHost) {
this.defaultMaxConnectionsPerHost = defaultMaxConnectionsPerHost;
}
}
配置文件:
<bean id="solrServer" class="com.duitang.search.core.SolrServerFactoryBean"> <property name="solrServerUrl" value="${solrServerUrl}"></property> <property name="soTimeout" value="1000"></property> <property name="connectionTimeout" value="100"></property> <property name="defaultMaxConnectionsPerHost" value="32"></property> <property name="maxTotalConnections" value="128"></property> </bean>
这里solrServerUrl是通过<context:property-placeholder location="/WEB-INF/*.properties"/>替换的