master c8b75e18a26c cached
32 files
52.4 KB
13.4k tokens
76 symbols
1 requests
Download .txt
Repository: heikehuan/springboot-multiple-dataSources
Branch: master
Commit: c8b75e18a26c
Files: 32
Total size: 52.4 KB

Directory structure:
gitextract_udxh3jb4/

├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── com/
        │       └── huan/
        │           ├── Application.java
        │           ├── config/
        │           │   ├── AbstractApplication.java
        │           │   ├── DataSourceAspect.java
        │           │   └── MyBatisConfig.java
        │           ├── controller/
        │           │   ├── TestDataSourceController.java
        │           │   └── WelcomeController.java
        │           ├── mapper/
        │           │   ├── UserDetailMapper.java
        │           │   └── UserInfoMapper.java
        │           ├── model/
        │           │   ├── UserDetail.java
        │           │   └── UserInfo.java
        │           ├── service/
        │           │   ├── CommonService.java
        │           │   ├── Test1Service.java
        │           │   ├── Test2Service.java
        │           │   └── impl/
        │           │       ├── CommonServiceImpl.java
        │           │       ├── Test1ServiceImpl.java
        │           │       └── Test2ServiceImpl.java
        │           └── util/
        │               ├── Constants.java
        │               ├── DatabaseContextHolder.java
        │               ├── DatabaseType.java
        │               └── DynamicDataSource.java
        └── resources/
            ├── application.yml
            ├── database1.sql
            ├── database2.sql
            ├── generator/
            │   ├── generatorConfig.xml
            │   └── mybatis_generator_config.properties
            ├── logback.xml
            └── mapper/
                ├── UserDetailMapper.xml
                └── UserInfoMapper.xml

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*.class

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.ear
.idea/
target/
*.iml

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# springboot-multiple-dataSources

### 前言 ###

spring-boot多数据源自动切换例子项目, 利用spring aop 切面,自动切换数据源。

CommonServiceImpl是公共处理类,Test1ServiceImpl和Test2ServiceImpl是两个数据源分别的业务处理类。定义DataSourceAspect类处理切面。

springboot-multiple-dataSources/src/main/resources目录下的database1.sql和database2.sql是2个数据源初始化脚本

### 软件环境 ###
IntelliJ IDEA 2016.3.3(或eclipse)

jdk 1.8

maven 3.3.9

### 使用的技术 ###

- spring-boot
- springmvc
- mybatis
- 通用mapper(一个非常好用的mybatis插件, 详细介绍见http://git.oschina.net/free/Mapper)

### 在IDE 中查看源码并运行 ###

**1. 在IntelliJ IDEA (推荐使用)**

File -> Import Project -> select springboot-multiple-dataSources folder -> create project form existing sources -> ...

**2. 在Eclipse**

File -> Import -> Existing Maven Projects -> ...


================================================
FILE: pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.huan</groupId>
    <artifactId>springboot-multiple-dataSources</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!--  MyBatis Generator  -->
        <!--  Java接口和实体类  -->
        <targetJavaProject>${basedir}/src/main/java</targetJavaProject>
        <targetMapperPackage>com.huan.mapper</targetMapperPackage>
        <targetModelPackage>com.huan.model</targetModelPackage>
        <!--  XML生成路径  -->
        <targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
        <targetXMLPackage>mapper</targetXMLPackage>
        <mysql.version>5.1.42</mysql.version>
        <junit.version>4.12</junit.version>
        <mapper.version>3.4.0</mapper.version>
        <pagehelper.version>4.1.6</pagehelper.version>
        <logback.version>1.1.7</logback.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>
        <!-- LogBack dependencies -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- springboot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- Mybatis Generator -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <!--通用Mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>${mapper.version}</version>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>${basedir}/src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>${mapper.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

================================================
FILE: src/main/java/com/huan/Application.java
================================================
package com.huan;

import com.huan.config.AbstractApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

import java.net.UnknownHostException;

@SpringBootApplication(scanBasePackages = "com.huan", exclude = {DataSourceAutoConfiguration.class})
public class Application extends AbstractApplication {

    public static void main(String[] args) throws UnknownHostException {
        SpringApplication app = new SpringApplication(Application.class);
        app.run(args);
//        abstractMain(app, args);
    }
}


================================================
FILE: src/main/java/com/huan/config/AbstractApplication.java
================================================
package com.huan.config;

import com.huan.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.SimpleCommandLinePropertySource;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;

/**
 * @author <a href="mailto:jean@eastcode.org">Jean Seurin</a>
 * @since 12/11/15 - 10:16
 */
public class AbstractApplication extends SpringBootServletInitializer {

    protected static final Logger logger = LoggerFactory.getLogger(AbstractApplication.class);
    protected static Environment staticEnv;
    @Autowired
    protected ConfigurableEnvironment env;

    protected static void abstractMain(SpringApplication app, String[] args) throws UnknownHostException {
        SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
        addDefaultProfile(app, source);
        //addLiquibaseScanPackages();
        staticEnv = app.run(args).getEnvironment();
        showAppInfo(staticEnv);
    }

    protected static void showAppInfo(final Environment env) throws UnknownHostException {
        String isSslEnabled = env.getProperty("server.ssl.enabled");
        String protocol = "http";
        if (isSslEnabled != null && "true".equals(isSslEnabled)) {
            protocol = "https";
        }
        logger.info("Access URLs:\n----------------------------------------------------------\n\t" +
                        "Local: \t\t" + protocol + "://127.0.0.1:{}\n\t" +
                        "External: \t" + protocol + "://{}:{}\n----------------------------------------------------------",
                env.getProperty("server.port"),
                InetAddress.getLocalHost().getHostAddress(),
                env.getProperty("server.port"));
    }

    /**
     * If no profile has been configured, set by default the "dev" profile.
     */
    protected static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
        if ((System.getProperty("spring.profiles.active") == null)
                && !source.containsProperty("spring.profiles.active")
                && !System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
            app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
        }
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(this.getClass());
    }

    /**
     * Initializes the application. Do some checks on profile configuration
     * <p>
     * Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
     * <p>
     */
    @PostConstruct
    public void initApplication() throws IOException {
        if (env.getActiveProfiles().length == 0) {
            logger.warn("No Spring profile configured, running with default configuration");
        } else {
            logger.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
            Collection activeProfiles = Arrays.asList(env.getActiveProfiles());
            if (activeProfiles.contains("dev") && activeProfiles.contains("prod")) {
                logger.error("You have misconfigured your application! It should not run with both the 'dev' and 'prod' profiles at the same time.");
            }
            if (activeProfiles.contains("prod") && activeProfiles.contains("fast")) {
                logger.error("You have misconfigured your application! It should not run with both the 'prod' and 'fast' profiles at the same time.");
            }
        }
    }
}


================================================
FILE: src/main/java/com/huan/config/DataSourceAspect.java
================================================
package com.huan.config;

import com.huan.service.Test1Service;
import com.huan.service.impl.Test1ServiceImpl;
import com.huan.util.DatabaseContextHolder;
import com.huan.util.DatabaseType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DataSourceAspect {

    /**
     * 使用空方法定义切点表达式
     */
    @Pointcut("execution(* com.huan.service.**.*(..))")
    public void declareJointPointExpression() {
    }

    @Before("declareJointPointExpression()")
    public void setDataSourceKey(JoinPoint point){
        //根据连接点所属的类实例,动态切换数据源
        if (point.getTarget() instanceof Test1Service
                || point.getTarget() instanceof Test1ServiceImpl) {
            DatabaseContextHolder.setDatabaseType(DatabaseType.test1);
        } else {//连接点所属的类实例是(当然,这一步也可以不写,因为defaultTargertDataSource就是该类所用的mytestdb)
            DatabaseContextHolder.setDatabaseType(DatabaseType.test2);
        }
    }
}

================================================
FILE: src/main/java/com/huan/config/MyBatisConfig.java
================================================
package com.huan.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.huan.util.DatabaseType;
import com.huan.util.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * springboot集成mybatis的基本入口 1)创建数据源(如果采用的是默认的tomcat-jdbc数据源,则不需要)
 * 2)创建SqlSessionFactory 3)配置事务管理器,除非需要使用事务,否则不用配置
 */
@Configuration // 该注解类似于spring配置文件
public class MyBatisConfig implements EnvironmentAware {

    private Environment environment;

    @Override
    public void setEnvironment(final Environment environment) {
        this.environment = environment;
    }

    /**
     * 创建数据源(数据源的名称:方法名可以取为XXXDataSource(),XXX为数据库名称,该名称也就是数据源的名称)
     */
    @Bean
    public DataSource test1DataSource() throws Exception {
        Properties props = new Properties();
        props.put("driverClassName", environment.getProperty("test1-datasource.driverClassName"));
        props.put("url", environment.getProperty("test1-datasource.url"));
        props.put("username", environment.getProperty("test1-datasource.username"));
        props.put("password", environment.getProperty("test1-datasource.password"));
        return DruidDataSourceFactory.createDataSource(props);
    }

    @Bean
    public DataSource test2DataSource() throws Exception {
        Properties props = new Properties();
        props.put("driverClassName", environment.getProperty("test2-datasource.driverClassName"));
        props.put("url", environment.getProperty("test2-datasource.url"));
        props.put("username", environment.getProperty("test2-datasource.username"));
        props.put("password", environment.getProperty("test2-datasource.password"));
        return DruidDataSourceFactory.createDataSource(props);
    }

    /**
     * @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错
     * @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)
     */
    @Bean
    @Primary
    public DynamicDataSource dataSource(@Qualifier("test1DataSource") DataSource test1DataSource,
                                        @Qualifier("test2DataSource") DataSource test2DataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DatabaseType.test1, test1DataSource);
        targetDataSources.put(DatabaseType.test2, test2DataSource);

        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
        dataSource.setDefaultTargetDataSource(test2DataSource);// 默认的datasource设置为myTestDbDataSource

        return dataSource;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setBasePackage("com.huan.mapper");
        Properties props = new Properties();
        props.setProperty("mappers", "tk.mybatis.mapper.common.Mapper");
        props.setProperty("IDENTITY", "MYSQL");
        props.setProperty("notEmpty", "true");
        scannerConfigurer.setProperties(props);
        return scannerConfigurer;
    }

    /**
     * 根据数据源创建SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(ds);// 指定数据源(这个必须有,否则报错)
        // 下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加
        fb.setTypeAliasesPackage("com.huan.model");// 指定基包
        fb.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));//

        return fb.getObject();
    }



    /**
     * 配置事务管理器
     */
    @Bean
    public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }


}

================================================
FILE: src/main/java/com/huan/controller/TestDataSourceController.java
================================================
package com.huan.controller;

import com.huan.model.UserDetail;
import com.huan.model.UserInfo;
import com.huan.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class TestDataSourceController {

    @Autowired
    private CommonService commonService;

    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    public List<UserInfo> selectUser() {
        System.out.println("查询第一个数据源");
        return commonService.selectUserInfo();
    }

    @RequestMapping(value = "/test2", method = RequestMethod.GET)
    public List<UserDetail> userDetail() {
        System.out.println("查询第二个数据源");
        return commonService.selectUserDetail();
    }

}

================================================
FILE: src/main/java/com/huan/controller/WelcomeController.java
================================================
package com.huan.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by huan on 2016/5/21.
 */
@RestController
public class WelcomeController {

    @RequestMapping("/")
    public Map welcome() {
        Map model = new HashMap();
        model.put("time", new Date());
        model.put("message", "Hello World");
        return model;
    }

}

================================================
FILE: src/main/java/com/huan/mapper/UserDetailMapper.java
================================================
package com.huan.mapper;

import com.huan.model.UserDetail;
import tk.mybatis.mapper.common.Mapper;

public interface UserDetailMapper extends Mapper<UserDetail> {
}

================================================
FILE: src/main/java/com/huan/mapper/UserInfoMapper.java
================================================
package com.huan.mapper;

import com.huan.model.UserInfo;

import java.util.List;

public interface UserInfoMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_info
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    int deleteByPrimaryKey(String id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_info
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    int insert(UserInfo record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_info
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    UserInfo selectByPrimaryKey(String id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_info
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    List<UserInfo> selectAll();

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_info
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    int updateByPrimaryKey(UserInfo record);
}

================================================
FILE: src/main/java/com/huan/model/UserDetail.java
================================================
package com.huan.model;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "user_detail")
public class UserDetail {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String qq;

    /**
     * @return id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return qq
     */
    public String getQq() {
        return qq;
    }

    /**
     * @param qq
     */
    public void setQq(String qq) {
        this.qq = qq;
    }
}

================================================
FILE: src/main/java/com/huan/model/UserInfo.java
================================================
package com.huan.model;

public class UserInfo {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user_info.id
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    private String id;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user_info.username
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    private String username;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user_info.net_name
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    private String netName;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user_info.job
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    private String job;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user_info.family_native_place
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    private String familyNativePlace;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user_info.mobile
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    private String mobile;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column user_info.email
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    private String email;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user_info.id
     *
     * @return the value of user_info.id
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public String getId() {
        return id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user_info.id
     *
     * @param id the value for user_info.id
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user_info.username
     *
     * @return the value of user_info.username
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public String getUsername() {
        return username;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user_info.username
     *
     * @param username the value for user_info.username
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user_info.net_name
     *
     * @return the value of user_info.net_name
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public String getNetName() {
        return netName;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user_info.net_name
     *
     * @param netName the value for user_info.net_name
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public void setNetName(String netName) {
        this.netName = netName;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user_info.job
     *
     * @return the value of user_info.job
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public String getJob() {
        return job;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user_info.job
     *
     * @param job the value for user_info.job
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public void setJob(String job) {
        this.job = job;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user_info.family_native_place
     *
     * @return the value of user_info.family_native_place
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public String getFamilyNativePlace() {
        return familyNativePlace;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user_info.family_native_place
     *
     * @param familyNativePlace the value for user_info.family_native_place
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public void setFamilyNativePlace(String familyNativePlace) {
        this.familyNativePlace = familyNativePlace;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user_info.mobile
     *
     * @return the value of user_info.mobile
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public String getMobile() {
        return mobile;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user_info.mobile
     *
     * @param mobile the value for user_info.mobile
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column user_info.email
     *
     * @return the value of user_info.email
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public String getEmail() {
        return email;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column user_info.email
     *
     * @param email the value for user_info.email
     *
     * @mbggenerated Fri May 27 01:50:31 CST 2016
     */
    public void setEmail(String email) {
        this.email = email;
    }
}

================================================
FILE: src/main/java/com/huan/service/CommonService.java
================================================
package com.huan.service;

import com.huan.model.UserDetail;
import com.huan.model.UserInfo;

import java.util.List;

/**
 * @author <a href="mailto:huanhuan.zhan@ptthink.com">詹欢欢</a>
 * @since 2016/7/5 - 22:20
 */
public interface CommonService {
    List<UserInfo> selectUserInfo();

    List<UserDetail> selectUserDetail();
}


================================================
FILE: src/main/java/com/huan/service/Test1Service.java
================================================
package com.huan.service;

import com.huan.model.UserInfo;

import java.util.List;

/**
 * @author <a href="mailto:huanhuan.zhan@ptthink.com">詹欢欢</a>
 * @since 2016/7/5 - 22:18
 */
public interface Test1Service {

    List<UserInfo> selectUserInfo();
}


================================================
FILE: src/main/java/com/huan/service/Test2Service.java
================================================
package com.huan.service;

import com.huan.model.UserDetail;

import java.util.List;

/**
 * @author <a href="mailto:huanhuan.zhan@ptthink.com">詹欢欢</a>
 * @since 2016/7/5 - 22:21
 */
public interface Test2Service {

    List<UserDetail> selectUserDetail();
}


================================================
FILE: src/main/java/com/huan/service/impl/CommonServiceImpl.java
================================================
package com.huan.service.impl;

import com.huan.model.UserDetail;
import com.huan.model.UserInfo;
import com.huan.service.CommonService;
import com.huan.service.Test1Service;
import com.huan.service.Test2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author <a href="mailto:huanhuan.zhan@ptthink.com">詹欢欢</a>
 * @since 2016/7/5 - 22:20
 */
@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private Test1Service test1Service;
    @Autowired
    private Test2Service test2Service;

    public List<UserInfo> selectUserInfo() {
        return test1Service.selectUserInfo();
    }

    public List<UserDetail> selectUserDetail() {
        return test2Service.selectUserDetail();
    }
}


================================================
FILE: src/main/java/com/huan/service/impl/Test1ServiceImpl.java
================================================
package com.huan.service.impl;

import com.huan.mapper.UserInfoMapper;
import com.huan.model.UserInfo;
import com.huan.service.Test1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class Test1ServiceImpl implements Test1Service {

    @Autowired
    private UserInfoMapper userInfoMapper;

    public List<UserInfo> selectUserInfo() {
        return userInfoMapper.selectAll();
    }
}

================================================
FILE: src/main/java/com/huan/service/impl/Test2ServiceImpl.java
================================================
package com.huan.service.impl;

import com.huan.mapper.UserDetailMapper;
import com.huan.model.UserDetail;
import com.huan.service.Test2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author <a href="mailto:huanhuan.zhan@ptthink.com">詹欢欢</a>
 * @since 2016/7/5 - 22:21
 */
@Service
public class Test2ServiceImpl implements Test2Service {

    @Autowired
    private UserDetailMapper userDetailMapper;

    public List<UserDetail> selectUserDetail() {
        return userDetailMapper.selectAll();
    }
}


================================================
FILE: src/main/java/com/huan/util/Constants.java
================================================
package com.huan.util;

/**
 * @author <a href="mailto:jean@eastcode.org">Jean Seurin</a>
 * @version $Id$
 * @since 13/08/15 - 18:36
 */
public class Constants {

    public static final boolean DEBUG = true;
    public static final String DATA_ENCODE = "utf-8";

    public static final String JSON_VIEW_STATUS_SUCCESS = "success";
    public static final String JSON_VIEW_STATUS_FAILED = "failed";
    public static final String JSON_VIEW_STATUS_ERROR = "error";
    public static final String JSON_VIEW_STATUS_UNAUTHORIZED = "unauthorized";

    public static final String SPRING_PROFILE_PRODUCTION = "prod";
    public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
    public static final String SPRING_PROFILE_TEST = "test";
    public static final String SPRING_PROFILE_FAST = "fast";
    public static final String SPRING_PROFILE_JSE = "jse";
    public static final String SPRING_PROFILE_STAGING = "staging";

    public static final String LOCAL_SERVER_URL = "http://localhost:8080";
}


================================================
FILE: src/main/java/com/huan/util/DatabaseContextHolder.java
================================================
package com.huan.util;

/**
 * 作用:
 * 1、保存一个线程安全的DatabaseType容器
 */
public class DatabaseContextHolder {
    private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();

    public static DatabaseType getDatabaseType(){
        return contextHolder.get();
    }

    public static void setDatabaseType(DatabaseType type) {
        contextHolder.set(type);
    }
}

================================================
FILE: src/main/java/com/huan/util/DatabaseType.java
================================================
package com.huan.util;

/**
 * 列出所有的数据源key(常用数据库名称来命名)
 * 注意:
 * 1)这里数据源与数据库是一对一的
 * 2)DatabaseType中的变量名称就是数据库的名称
 */
public enum DatabaseType {
    test1,
    test2
}

================================================
FILE: src/main/java/com/huan/util/DynamicDataSource.java
================================================
package com.huan.util;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 动态数据源(需要继承AbstractRoutingDataSource)
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    protected Object determineCurrentLookupKey() {
        return DatabaseContextHolder.getDatabaseType();
    }
}

================================================
FILE: src/main/resources/application.yml
================================================
server:
    port: 8080

test1-datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/database1?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    username: root
    password: root
test2-datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/database2?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    username: root
    password: root


================================================
FILE: src/main/resources/database1.sql
================================================
/*
SQLyog Ultimate v11.27 (32 bit)
MySQL - 5.6.27-log : Database - database1
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE = '' */;

/*!40014 SET @OLD_UNIQUE_CHECKS = @@UNIQUE_CHECKS, UNIQUE_CHECKS = 0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS = 0 */;
/*!40101 SET @OLD_SQL_MODE = @@SQL_MODE, SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES = @@SQL_NOTES, SQL_NOTES = 0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS */`database1` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `database1`;

/*Table structure for table `user_info` */

DROP TABLE IF EXISTS `user_info`;

CREATE TABLE `user_info` (
  `id`                  VARCHAR(100) NOT NULL,
  `username`            VARCHAR(255) DEFAULT NULL,
  `net_name`            VARCHAR(255) DEFAULT NULL,
  `job`                 VARCHAR(255) DEFAULT NULL,
  `family_native_place` VARCHAR(255) DEFAULT NULL,
  `mobile`              VARCHAR(100) DEFAULT NULL,
  `email`               VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

/*Data for the table `user_info` */

INSERT INTO `user_info` (`id`, `username`, `net_name`, `job`, `family_native_place`, `mobile`, `email`)
VALUES ('1', '詹欢欢', 'heikehuan', 'java后端开发', '湖北省孝感市', '15010699876', '873089996@qq.com');

/*!40101 SET SQL_MODE = @OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS = @OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS = @OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES = @OLD_SQL_NOTES */;


================================================
FILE: src/main/resources/database2.sql
================================================
/*
SQLyog Ultimate v11.27 (32 bit)
MySQL - 5.6.27-log : Database - database2
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`database2` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `database2`;

/*Table structure for table `user_detail` */

DROP TABLE IF EXISTS `user_detail`;

CREATE TABLE `user_detail` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `qq` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `user_detail` */

insert  into `user_detail`(`id`,`name`,`qq`) values (1,'lululu','1231231');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;


================================================
FILE: src/main/resources/generator/generatorConfig.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <properties resource="generator/mybatis_generator_config.properties"/>

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <plugin type="${mapper.plugin}">
            <property name="mappers" value="${mapper.Mapper}"/>
        </plugin>

        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.user}"
                        password="${jdbc.password}">
        </jdbcConnection>

        <javaModelGenerator targetPackage="${targetModelPackage}" targetProject="${targetJavaProject}"/>

        <sqlMapGenerator targetPackage="${targetXMLPackage}" targetProject="${targetResourcesProject}"/>

        <javaClientGenerator targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}"
                             type="XMLMAPPER"/>

        <table tableName="%">
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>


================================================
FILE: src/main/resources/generator/mybatis_generator_config.properties
================================================
#数据库连接
jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url =jdbc\:mysql\://localhost\:3306/huan_blog_test?useUnicode\=true&characterEncoding\=utf8
jdbc.user=root
jdbc.password=root

#c3p0
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=100
jdbc.testConnection=true

# 通用mapper
mapper.plugin = tk.mybatis.mapper.generator.MapperPlugin
mapper.Mapper = tk.mybatis.mapper.common.Mapper


================================================
FILE: src/main/resources/logback.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <logger name="org.springframework" level="debug" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>

    <logger name="com.huan" level="debug" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>

    <root level="error">
        <appender-ref ref="STDOUT"/>
    </root>

</configuration>

================================================
FILE: src/main/resources/mapper/UserDetailMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.huan.mapper.UserDetailMapper">
    <resultMap id="BaseResultMap" type="com.huan.model.UserDetail">
        <!--
          WARNING - @mbggenerated
        -->
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="qq" property="qq" jdbcType="VARCHAR"/>
    </resultMap>
</mapper>

================================================
FILE: src/main/resources/mapper/UserInfoMapper.xml
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.huan.mapper.UserInfoMapper">
  <resultMap id="BaseResultMap" type="com.huan.model.UserInfo">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri May 27 01:50:31 CST 2016.
    -->
    <id column="id" property="id" jdbcType="VARCHAR"/>
    <result column="username" property="username" jdbcType="VARCHAR"/>
    <result column="net_name" property="netName" jdbcType="VARCHAR"/>
    <result column="job" property="job" jdbcType="VARCHAR"/>
    <result column="family_native_place" property="familyNativePlace" jdbcType="VARCHAR"/>
    <result column="mobile" property="mobile" jdbcType="VARCHAR"/>
    <result column="email" property="email" jdbcType="VARCHAR"/>
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri May 27 01:50:31 CST 2016.
    -->
    delete from user_info
    where id = #{id,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.huan.model.UserInfo">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri May 27 01:50:31 CST 2016.
    -->
    <selectKey resultType="java.lang.String" keyProperty="id" order="AFTER">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into user_info (username, net_name, job,
    family_native_place, mobile, email
    )
    values (#{username,jdbcType=VARCHAR}, #{netName,jdbcType=VARCHAR}, #{job,jdbcType=VARCHAR},
    #{familyNativePlace,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}
    )
  </insert>
  <update id="updateByPrimaryKey" parameterType="com.huan.model.UserInfo">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri May 27 01:50:31 CST 2016.
    -->
    update user_info
    set username = #{username,jdbcType=VARCHAR},
      net_name = #{netName,jdbcType=VARCHAR},
      job = #{job,jdbcType=VARCHAR},
      family_native_place = #{familyNativePlace,jdbcType=VARCHAR},
      mobile = #{mobile,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR}
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri May 27 01:50:31 CST 2016.
    -->
    select id, username, net_name, job, family_native_place, mobile, email
    from user_info
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <select id="selectAll" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri May 27 01:50:31 CST 2016.
    -->
    select id, username, net_name, job, family_native_place, mobile, email
    from user_info
  </select>
</mapper>
Download .txt
gitextract_udxh3jb4/

├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── com/
        │       └── huan/
        │           ├── Application.java
        │           ├── config/
        │           │   ├── AbstractApplication.java
        │           │   ├── DataSourceAspect.java
        │           │   └── MyBatisConfig.java
        │           ├── controller/
        │           │   ├── TestDataSourceController.java
        │           │   └── WelcomeController.java
        │           ├── mapper/
        │           │   ├── UserDetailMapper.java
        │           │   └── UserInfoMapper.java
        │           ├── model/
        │           │   ├── UserDetail.java
        │           │   └── UserInfo.java
        │           ├── service/
        │           │   ├── CommonService.java
        │           │   ├── Test1Service.java
        │           │   ├── Test2Service.java
        │           │   └── impl/
        │           │       ├── CommonServiceImpl.java
        │           │       ├── Test1ServiceImpl.java
        │           │       └── Test2ServiceImpl.java
        │           └── util/
        │               ├── Constants.java
        │               ├── DatabaseContextHolder.java
        │               ├── DatabaseType.java
        │               └── DynamicDataSource.java
        └── resources/
            ├── application.yml
            ├── database1.sql
            ├── database2.sql
            ├── generator/
            │   ├── generatorConfig.xml
            │   └── mybatis_generator_config.properties
            ├── logback.xml
            └── mapper/
                ├── UserDetailMapper.xml
                └── UserInfoMapper.xml
Download .txt
SYMBOL INDEX (76 symbols across 22 files)

FILE: src/main/java/com/huan/Application.java
  class Application (line 10) | @SpringBootApplication(scanBasePackages = "com.huan", exclude = {DataSou...
    method main (line 13) | public static void main(String[] args) throws UnknownHostException {

FILE: src/main/java/com/huan/config/AbstractApplication.java
  class AbstractApplication (line 25) | public class AbstractApplication extends SpringBootServletInitializer {
    method abstractMain (line 32) | protected static void abstractMain(SpringApplication app, String[] arg...
    method showAppInfo (line 40) | protected static void showAppInfo(final Environment env) throws Unknow...
    method addDefaultProfile (line 57) | protected static void addDefaultProfile(SpringApplication app, SimpleC...
    method configure (line 65) | @Override
    method initApplication (line 76) | @PostConstruct

FILE: src/main/java/com/huan/config/DataSourceAspect.java
  class DataSourceAspect (line 13) | @Aspect
    method declareJointPointExpression (line 20) | @Pointcut("execution(* com.huan.service.**.*(..))")
    method setDataSourceKey (line 24) | @Before("declareJointPointExpression()")

FILE: src/main/java/com/huan/config/MyBatisConfig.java
  class MyBatisConfig (line 27) | @Configuration // 该注解类似于spring配置文件
    method setEnvironment (line 32) | @Override
    method test1DataSource (line 40) | @Bean
    method test2DataSource (line 50) | @Bean
    method dataSource (line 64) | @Bean
    method mapperScannerConfigurer (line 79) | @Bean
    method sqlSessionFactory (line 94) | @Bean
    method transactionManager (line 112) | @Bean

FILE: src/main/java/com/huan/controller/TestDataSourceController.java
  class TestDataSourceController (line 13) | @RestController
    method selectUser (line 19) | @RequestMapping(value = "/test1", method = RequestMethod.GET)
    method userDetail (line 25) | @RequestMapping(value = "/test2", method = RequestMethod.GET)

FILE: src/main/java/com/huan/controller/WelcomeController.java
  class WelcomeController (line 13) | @RestController
    method welcome (line 16) | @RequestMapping("/")

FILE: src/main/java/com/huan/mapper/UserDetailMapper.java
  type UserDetailMapper (line 6) | public interface UserDetailMapper extends Mapper<UserDetail> {

FILE: src/main/java/com/huan/mapper/UserInfoMapper.java
  type UserInfoMapper (line 7) | public interface UserInfoMapper {
    method deleteByPrimaryKey (line 14) | int deleteByPrimaryKey(String id);
    method insert (line 22) | int insert(UserInfo record);
    method selectByPrimaryKey (line 30) | UserInfo selectByPrimaryKey(String id);
    method selectAll (line 38) | List<UserInfo> selectAll();
    method updateByPrimaryKey (line 46) | int updateByPrimaryKey(UserInfo record);

FILE: src/main/java/com/huan/model/UserDetail.java
  class UserDetail (line 8) | @Table(name = "user_detail")
    method getId (line 21) | public Long getId() {
    method setId (line 28) | public void setId(Long id) {
    method getName (line 35) | public String getName() {
    method setName (line 42) | public void setName(String name) {
    method getQq (line 49) | public String getQq() {
    method setQq (line 56) | public void setQq(String qq) {

FILE: src/main/java/com/huan/model/UserInfo.java
  class UserInfo (line 3) | public class UserInfo {
    method getId (line 68) | public String getId() {
    method setId (line 80) | public void setId(String id) {
    method getUsername (line 92) | public String getUsername() {
    method setUsername (line 104) | public void setUsername(String username) {
    method getNetName (line 116) | public String getNetName() {
    method setNetName (line 128) | public void setNetName(String netName) {
    method getJob (line 140) | public String getJob() {
    method setJob (line 152) | public void setJob(String job) {
    method getFamilyNativePlace (line 164) | public String getFamilyNativePlace() {
    method setFamilyNativePlace (line 176) | public void setFamilyNativePlace(String familyNativePlace) {
    method getMobile (line 188) | public String getMobile() {
    method setMobile (line 200) | public void setMobile(String mobile) {
    method getEmail (line 212) | public String getEmail() {
    method setEmail (line 224) | public void setEmail(String email) {

FILE: src/main/java/com/huan/service/CommonService.java
  type CommonService (line 12) | public interface CommonService {
    method selectUserInfo (line 13) | List<UserInfo> selectUserInfo();
    method selectUserDetail (line 15) | List<UserDetail> selectUserDetail();

FILE: src/main/java/com/huan/service/Test1Service.java
  type Test1Service (line 11) | public interface Test1Service {
    method selectUserInfo (line 13) | List<UserInfo> selectUserInfo();

FILE: src/main/java/com/huan/service/Test2Service.java
  type Test2Service (line 11) | public interface Test2Service {
    method selectUserDetail (line 13) | List<UserDetail> selectUserDetail();

FILE: src/main/java/com/huan/service/impl/CommonServiceImpl.java
  class CommonServiceImpl (line 17) | @Service
    method selectUserInfo (line 25) | public List<UserInfo> selectUserInfo() {
    method selectUserDetail (line 29) | public List<UserDetail> selectUserDetail() {

FILE: src/main/java/com/huan/service/impl/Test1ServiceImpl.java
  class Test1ServiceImpl (line 11) | @Service
    method selectUserInfo (line 17) | public List<UserInfo> selectUserInfo() {

FILE: src/main/java/com/huan/service/impl/Test2ServiceImpl.java
  class Test2ServiceImpl (line 15) | @Service
    method selectUserDetail (line 21) | public List<UserDetail> selectUserDetail() {

FILE: src/main/java/com/huan/util/Constants.java
  class Constants (line 8) | public class Constants {

FILE: src/main/java/com/huan/util/DatabaseContextHolder.java
  class DatabaseContextHolder (line 7) | public class DatabaseContextHolder {
    method getDatabaseType (line 10) | public static DatabaseType getDatabaseType(){
    method setDatabaseType (line 14) | public static void setDatabaseType(DatabaseType type) {

FILE: src/main/java/com/huan/util/DatabaseType.java
  type DatabaseType (line 9) | public enum DatabaseType {

FILE: src/main/java/com/huan/util/DynamicDataSource.java
  class DynamicDataSource (line 8) | public class DynamicDataSource extends AbstractRoutingDataSource {
    method determineCurrentLookupKey (line 9) | protected Object determineCurrentLookupKey() {

FILE: src/main/resources/database1.sql
  type `user_info` (line 24) | CREATE TABLE `user_info` (

FILE: src/main/resources/database2.sql
  type `user_detail` (line 23) | CREATE TABLE `user_detail` (
Condensed preview — 32 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (59K chars).
[
  {
    "path": ".gitignore",
    "chars": 210,
    "preview": "*.class\n\n# Mobile Tools for Java (J2ME)\n.mtj.tmp/\n\n# Package Files #\n*.jar\n*.war\n*.ear\n.idea/\ntarget/\n*.iml\n\n# virtual m"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 720,
    "preview": "# springboot-multiple-dataSources\n\n### 前言 ###\n\nspring-boot多数据源自动切换例子项目, 利用spring aop 切面,自动切换数据源。\n\nCommonServiceImpl是公共处理"
  },
  {
    "path": "pom.xml",
    "chars": 6430,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xmlns=\"ht"
  },
  {
    "path": "src/main/java/com/huan/Application.java",
    "chars": 673,
    "preview": "package com.huan;\n\nimport com.huan.config.AbstractApplication;\nimport org.springframework.boot.SpringApplication;\nimport"
  },
  {
    "path": "src/main/java/com/huan/config/AbstractApplication.java",
    "chars": 4078,
    "preview": "package com.huan.config;\n\nimport com.huan.util.Constants;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimpor"
  },
  {
    "path": "src/main/java/com/huan/config/DataSourceAspect.java",
    "chars": 1096,
    "preview": "package com.huan.config;\n\nimport com.huan.service.Test1Service;\nimport com.huan.service.impl.Test1ServiceImpl;\nimport co"
  },
  {
    "path": "src/main/java/com/huan/config/MyBatisConfig.java",
    "chars": 4646,
    "preview": "package com.huan.config;\n\nimport com.alibaba.druid.pool.DruidDataSourceFactory;\nimport com.huan.util.DatabaseType;\nimpor"
  },
  {
    "path": "src/main/java/com/huan/controller/TestDataSourceController.java",
    "chars": 932,
    "preview": "package com.huan.controller;\n\nimport com.huan.model.UserDetail;\nimport com.huan.model.UserInfo;\nimport com.huan.service."
  },
  {
    "path": "src/main/java/com/huan/controller/WelcomeController.java",
    "chars": 521,
    "preview": "package com.huan.controller;\n\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework."
  },
  {
    "path": "src/main/java/com/huan/mapper/UserDetailMapper.java",
    "chars": 165,
    "preview": "package com.huan.mapper;\n\nimport com.huan.model.UserDetail;\nimport tk.mybatis.mapper.common.Mapper;\n\npublic interface Us"
  },
  {
    "path": "src/main/java/com/huan/mapper/UserInfoMapper.java",
    "chars": 1270,
    "preview": "package com.huan.mapper;\n\nimport com.huan.model.UserInfo;\n\nimport java.util.List;\n\npublic interface UserInfoMapper {\n   "
  },
  {
    "path": "src/main/java/com/huan/model/UserDetail.java",
    "chars": 927,
    "preview": "package com.huan.model;\n\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax."
  },
  {
    "path": "src/main/java/com/huan/model/UserInfo.java",
    "chars": 6337,
    "preview": "package com.huan.model;\n\npublic class UserInfo {\n    /**\n     * This field was generated by MyBatis Generator.\n     * Th"
  },
  {
    "path": "src/main/java/com/huan/service/CommonService.java",
    "chars": 329,
    "preview": "package com.huan.service;\n\nimport com.huan.model.UserDetail;\nimport com.huan.model.UserInfo;\n\nimport java.util.List;\n\n/*"
  },
  {
    "path": "src/main/java/com/huan/service/Test1Service.java",
    "chars": 253,
    "preview": "package com.huan.service;\n\nimport com.huan.model.UserInfo;\n\nimport java.util.List;\n\n/**\n * @author <a href=\"mailto:huanh"
  },
  {
    "path": "src/main/java/com/huan/service/Test2Service.java",
    "chars": 259,
    "preview": "package com.huan.service;\n\nimport com.huan.model.UserDetail;\n\nimport java.util.List;\n\n/**\n * @author <a href=\"mailto:hua"
  },
  {
    "path": "src/main/java/com/huan/service/impl/CommonServiceImpl.java",
    "chars": 825,
    "preview": "package com.huan.service.impl;\n\nimport com.huan.model.UserDetail;\nimport com.huan.model.UserInfo;\nimport com.huan.servic"
  },
  {
    "path": "src/main/java/com/huan/service/impl/Test1ServiceImpl.java",
    "chars": 496,
    "preview": "package com.huan.service.impl;\n\nimport com.huan.mapper.UserInfoMapper;\nimport com.huan.model.UserInfo;\nimport com.huan.s"
  },
  {
    "path": "src/main/java/com/huan/service/impl/Test2ServiceImpl.java",
    "chars": 608,
    "preview": "package com.huan.service.impl;\n\nimport com.huan.mapper.UserDetailMapper;\nimport com.huan.model.UserDetail;\nimport com.hu"
  },
  {
    "path": "src/main/java/com/huan/util/Constants.java",
    "chars": 1006,
    "preview": "package com.huan.util;\n\n/**\n * @author <a href=\"mailto:jean@eastcode.org\">Jean Seurin</a>\n * @version $Id$\n * @since 13/"
  },
  {
    "path": "src/main/java/com/huan/util/DatabaseContextHolder.java",
    "chars": 387,
    "preview": "package com.huan.util;\n\n/**\n * 作用:\n * 1、保存一个线程安全的DatabaseType容器\n */\npublic class DatabaseContextHolder {\n    private sta"
  },
  {
    "path": "src/main/java/com/huan/util/DatabaseType.java",
    "chars": 167,
    "preview": "package com.huan.util;\n\n/**\n * 列出所有的数据源key(常用数据库名称来命名)\n * 注意:\n * 1)这里数据源与数据库是一对一的\n * 2)DatabaseType中的变量名称就是数据库的名称\n */\npu"
  },
  {
    "path": "src/main/java/com/huan/util/DynamicDataSource.java",
    "chars": 331,
    "preview": "package com.huan.util;\n\nimport org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;\n\n/**\n * 动态数据源(需要继承A"
  },
  {
    "path": "src/main/resources/application.yml",
    "chars": 426,
    "preview": "server:\n    port: 8080\n\ntest1-datasource:\n    driverClassName: com.mysql.jdbc.Driver\n    url: jdbc:mysql://localhost:330"
  },
  {
    "path": "src/main/resources/database1.sql",
    "chars": 1587,
    "preview": "/*\nSQLyog Ultimate v11.27 (32 bit)\nMySQL - 5.6.27-log : Database - database1\n*******************************************"
  },
  {
    "path": "src/main/resources/database2.sql",
    "chars": 1222,
    "preview": "/*\r\nSQLyog Ultimate v11.27 (32 bit)\r\nMySQL - 5.6.27-log : Database - database2\r\n****************************************"
  },
  {
    "path": "src/main/resources/generator/generatorConfig.xml",
    "chars": 1400,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<!DOCTYPE generatorConfiguration\n        PUBLIC \"-//mybatis.org//DTD MyBatis Gen"
  },
  {
    "path": "src/main/resources/generator/mybatis_generator_config.properties",
    "chars": 391,
    "preview": "#数据库连接\njdbc.driverClass = com.mysql.jdbc.Driver\njdbc.url =jdbc\\:mysql\\://localhost\\:3306/huan_blog_test?useUnicode\\=true"
  },
  {
    "path": "src/main/resources/logback.xml",
    "chars": 671,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAp"
  },
  {
    "path": "src/main/resources/mapper/UserDetailMapper.xml",
    "chars": 544,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org"
  },
  {
    "path": "src/main/resources/mapper/UserInfoMapper.xml",
    "chars": 3408,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org"
  }
]

About this extraction

This page contains the full source code of the heikehuan/springboot-multiple-dataSources GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 32 files (52.4 KB), approximately 13.4k tokens, and a symbol index with 76 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!