Spring Factorybean Application

Source: Internet
Author: User

There are two types of beans in Spring, one is a normal bean and the other is the factory bean, the Factorybean. Unlike a normal bean, Factorybean returns an object that is not an instance of the specified class, but the object returned by the GetObject method of the Factorybean.

This article simply analyzes the use of factory Factorybean.

Factorybean Interface Definition
package org.springframework.beans.factory;public interface FactoryBean<T> { T getObject() throws Exception; Class<?> getObjectType(); boolean isSingleton();}
Application Scenarios

Factorybean is usually used to create more complex beans, the general bean directly with the XML configuration, but if the creation of a bean involves a lot of other beans and complex logic, with XML configuration is difficult, you can consider using Factorybean.

Application case

Many open source projects use Factorybean when integrating spring, such as MYBATIS3, which provides the Mybatis-spring project org.mybatis.spring.SqlSessionFactoryBean :

<BeanId="Tradesqlsessionfactory"class="Org.mybatis.spring.SqlSessionFactoryBean" ><PropertyName="DataSource"ref= "trade"/> < property name= "mapperLocations" value= "Classpath*:mapper/trade/*mapper.xml"/> <property name=  "configlocation" value= "classpath: Mybatis-config.xml "/> <property  Name= "typealiasespackage" value= " Com.bytebeats.mybatis3.domain.trade "/> </BEAN>   

org.mybatis.spring.SqlSessionFactoryBeanAs follows:

package org.mybatis.spring;public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {private static final Log LOGGER = LogFactory.getLog(SqlSessionFactoryBean.class); ......}

In addition, Ali Open source distributed service Framework Dubbo in the consumer also used to Factorybean:

<Beansxmlns="Http://www.springframework.org/schema/beans"Xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xmlns:dubbo="Http://code.alibabatech.com/schema/dubbo"xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd Http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd "><!--Current application information--<dubbo: Application name= "Demo-consumer"/> <!--Exposure service agreement configured--<dubbo: Protocol name= "Dubbo" port= "20813"/> <!--Exposure Service configuration--<dubbo:reference id= "Demoservice" interface= "Com.alibaba.dubbo.config.spring.api.DemoService"/ > </BEANS>       

<dubbo:referenceThe corresponding Bean is the com.alibaba.dubbo.config.spring.ReferenceBean class, as follows:

public class ReferenceBean<T> extends ReferenceConfig<T> implements FactoryBean, ApplicationContextAware, InitializingBean, DisposableBean {}
Practice

The current micro-service is becoming popular, project development inevitably need to call some other system interface, this time to choose a suitable HTTP client library is very critical, I project development using Square Open source Okhttp, about Okhttp can refer OkHttp Recipes
The API for Okhttp itself has been very useful, combining spring with the purpose of reuse in other projects, and has made some encapsulation of the okhttp creation process, such as time-outs, connection pool size, HTTP proxies, and so on.

Maven dependencies:

<dependency>            <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.6.0</version></dependency>

First, the Okhttpclientfactorybean, the code is as follows:

Package com.bytebeats.codelab.http.okhttp;Import Com.bytebeats.codelab.http.util.StringUtils;Import okhttp3.*;Import Org.springframework.beans.factory.DisposableBean;Import Org.springframework.beans.factory.FactoryBean;Import java.io.IOException;Import java.net.InetSocketAddress;Import Java.net.Proxy;Import Java.util.concurrent.TimeUnit;/** * ${description} * *@author Ricky Fung *@create 2017-03-04 22:18 * *PublicClassOkhttpclientfactorybeanImplementsFactorybean,Disposablebean {Privateint connecttimeout;Privateint readtimeout;Privateint writetimeout;/**http Proxy config**/Private String host;Privateint port;Private String username;private String password;/**okhttpclient instance**/Private Okhttpclient client;@OverridePublic ObjectGetObject()Throws Exception {ConnectionPool pool =New ConnectionPool (5,Ten, 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 () {@OverridePublic RequestAuthenticate(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; }@OverridePublic class<?> Getobjecttype () {return okhttpclient.class; }@OverridePublicBooleanIssingleton() {ReturnTrue }@OverridePublicvoidDestroy()Throws Exception {if (client!=NULL) {Client.connectionpool (). Evictall (); Client.dispatcher (). Executorservice (). shutdown (); Client.cache (). Close (); Client =Null } }PublicvoidSetconnecttimeout(int connecttimeout) {This.connecttimeout = ConnectTimeout; }PublicvoidSetreadtimeout(int readtimeout) {This.readtimeout = ReadTimeout; }PublicvoidSetwritetimeout(int writetimeout) {This.writetimeout = WriteTimeout; }Publicvoidsethost (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; }} 

Reference Applicationcontext.xml in the project:

<?xml version="1.0" encoding="UTF-8"?><Beansxmlns="Http://www.springframework.org/schema/beans"Xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xmlns:context="Http://www.springframework.org/schema/context"Xmlns:util="Http://www.springframework.org/schema/util"xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http:/ /www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd/HTTP Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "><BeanId="Okhttpclient"class="Com.bytebeats.codelab.http.okhttp.OkHttpClientFactoryBean" ><PropertyName="ConnectTimeout"Value="/>"<PropertyName="ReadTimeout"Value="/>"<PropertyName="WriteTimeout"Value="/>"<Propertyname= "host" value=  "/> <property name= "port" value=  "0"/> <property name= "username" value=" "/> <property name=< Span class= "hljs-string" > "password" value= "/> </bean></beans>   

Write a test class test:

    @Resource    private OkHttpClient client;    public void run() throws Exception { Request request = new Request.Builder() .url("https://www.baidu.com/") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }


Fx_sky
Links: https://www.jianshu.com/p/6f0a59623090
Source: Pinterest
The copyright of the book is owned by the author, and any form of reprint should be contacted by the author for authorization and attribution.

Spring Factorybean Application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.