Mybatis源码阅读之PooledDataSourceFactory

源码一:PooledDataSourceFactory 继承自UnpooledDataSourceFactory 

package org.apache.ibatis.datasource.pooled;

import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;

/**

 * @author Clinton Begin

 */

public class PooledDataSourceFactory extends UnpooledDataSourceFactory {

  public PooledDataSourceFactory() {

    this.dataSource = new PooledDataSource();

  }

}

源码二:UnpooledDataSourceFactory 实现了DataSourceFactory 接口

package org.apache.ibatis.datasource.unpooled;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.DataSourceException;

import org.apache.ibatis.datasource.DataSourceFactory;

import org.apache.ibatis.reflection.MetaObject;

import org.apache.ibatis.reflection.SystemMetaObject;

/**

 * @author Clinton Begin

 */

public class UnpooledDataSourceFactory implements DataSourceFactory {

  private static final String DRIVER_PROPERTY_PREFIX = "driver.";

  private static final int DRIVER_PROPERTY_PREFIX_LENGTH = DRIVER_PROPERTY_PREFIX.length();

  protected DataSource dataSource;

  public UnpooledDataSourceFactory() {

    this.dataSource = new UnpooledDataSource();

  }

  @Override

  public void setProperties(Properties properties) {

    Properties driverProperties = new Properties();

    MetaObject metaDataSource = SystemMetaObject.forObject(dataSource);

    for (Object key : properties.keySet()) {

      String propertyName = (String) key;

      if (propertyName.startsWith(DRIVER_PROPERTY_PREFIX)) {

        String value = properties.getProperty(propertyName);

        driverProperties.setProperty(propertyName.substring(DRIVER_PROPERTY_PREFIX_LENGTH), value);

      } else if (metaDataSource.hasSetter(propertyName)) {

        String value = (String) properties.get(propertyName);

        Object convertedValue = convertValue(metaDataSource, propertyName, value);

        metaDataSource.setValue(propertyName, convertedValue);

      } else {

        throw new DataSourceException("Unknown DataSource property: " + propertyName);

      }

    }

    if (driverProperties.size() > 0) {

      metaDataSource.setValue("driverProperties", driverProperties);

    }

  }

  @Override

  public DataSource getDataSource() {

    return dataSource;

  }

  private Object convertValue(MetaObject metaDataSource, String propertyName, String value) {

    Object convertedValue = value;

    Class<?> targetType = metaDataSource.getSetterType(propertyName);

    if (targetType == Integer.class || targetType == int.class) {

      convertedValue = Integer.valueOf(value);

    } else if (targetType == Long.class || targetType == long.class) {

      convertedValue = Long.valueOf(value);

    } else if (targetType == Boolean.class || targetType == boolean.class) {

      convertedValue = Boolean.valueOf(value);

    }

    return convertedValue;

  }

}

猜你喜欢

转载自gaojingsong.iteye.com/blog/2337432