1. 程式人生 > >Spring FactoryBean介面

Spring FactoryBean介面

如果一個bean實現FactoryBean,那麼它就不是一個簡單的bean,類似於java模式中的工廠模式,用於生產不同的Object。

舉例

 public class OkHttpClientFactoryBean implements FactoryBean, DisposableBean {
	private int connectTimeout;
	private int readTimeout;
	private int writeTimeout;
	/**
	 * http proxy config
	 **/
	private String host;
	private int port;
private String username; private String password; /** * OkHttpClient instance **/ private OkHttpClient client; @Override public Object getObject() throws Exception { ConnectionPool pool = new ConnectionPool(5, 10, TimeUnit.SECONDS); OkHttpClient.Builder builder = new OkHttpClient.Builder
(); builder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).readTimeout(readTimeout, TimeUnit.MILLISECONDS).writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).connectionPool(pool); if (StringUtils.isNotBlank(host) && port > 0) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress
(host, port)); builder.proxy(proxy); } if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) { Authenticator proxyAuthenticator = new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { String credential = Credentials.basic(username, password); return response.request().newBuilder().header("Proxy-Authorization", credential).build(); } }; builder.proxyAuthenticator(proxyAuthenticator); } client = builder.build(); return client; } @Override public Class<?> getObjectType() { return OkHttpClient.class; } @Override public boolean isSingleton() { return true; } @Override public void destroy() throws Exception { if (client != null) { client.connectionPool().evictAll(); client.dispatcher().executorService().shutdown(); client.cache().close(); client = null; } } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public void setWriteTimeout(int writeTimeout) { this.writeTimeout = writeTimeout; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } }