42.2 Spring Boot多數據源

(5)編寫多數據源註冊文件;java

       這個注入是最核心的部分,咱們先看代碼:spring

com.kfit.config.datasource.multids.MultipleDataSourceBeanDefinitionRegistryPostProcessor:sql

package com.kfit.config.datasource.multids;apache

 

import java.util.HashMap;tomcat

import java.util.Map;app

import java.util.Map.Entry;ide

 

import javax.sql.DataSource;post

 

importorg.springframework.beans.BeansException;this

importorg.springframework.beans.MutablePropertyValues;url

importorg.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;

importorg.springframework.beans.factory.config.BeanDefinition;

importorg.springframework.beans.factory.config.BeanDefinitionHolder;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

importorg.springframework.beans.factory.support.BeanDefinitionReaderUtils;

importorg.springframework.beans.factory.support.BeanDefinitionRegistry;

importorg.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;

importorg.springframework.beans.factory.support.BeanNameGenerator;

importorg.springframework.boot.bind.RelaxedPropertyResolver;

importorg.springframework.context.EnvironmentAware;

importorg.springframework.context.annotation.AnnotationBeanNameGenerator;

importorg.springframework.context.annotation.AnnotationConfigUtils;

importorg.springframework.context.annotation.AnnotationScopeMetadataResolver;

importorg.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.ScopeMetadata;

importorg.springframework.context.annotation.ScopeMetadataResolver;

importorg.springframework.core.env.Environment;

 

/**

 * 動態建立多數據源註冊到Spring中

 *

 接口:BeanDefinitionRegistryPostProcessor只要是注入bean,

 在上一節介紹過使用方式;

 

 接口:接口 EnvironmentAware 重寫方法 setEnvironment

 能夠在工程啓動時,獲取到系統環境變量和application配置文件中的變量。 

這個第24節介紹過.

 

 方法的執行順序是:

 

 setEnvironment()-->postProcessBeanDefinitionRegistry()-->postProcessBeanFactory()

 

 

 *

 * @author Angel(QQ:412887952)

 * @version v.0.1

 */

@Configuration

publicclassMultipleDataSourceBeanDefinitionRegistryPostProcessor implementsBeanDefinitionRegistryPostProcessor,EnvironmentAware{

 

      

       //做用域對象.

       privateScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();

       //bean名稱生成器.

       privateBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();

             

       //如配置文件中未指定數據源類型,使用該默認值

   privatestaticfinal Object DATASOURCE_TYPE_DEFAULT = "org.apache.tomcat.jdbc.pool.DataSource";

       //  private static final ObjectDATASOURCE_TYPE_DEFAULT = "com.zaxxer.hikari.HikariDataSource";

             

       // 存放DataSource配置的集合;

   private Map<String, Map<String, Object>> dataSourceMap = newHashMap<String, Map<String, Object>>();

      

      

       @Override

       publicvoidpostProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

              System.out.println("MultipleDataSourceBeanDefinitionRegistryPostProcessor.postProcessBeanFactory()");

              //設置爲主數據源;

              beanFactory.getBeanDefinition("dataSource").setPrimary(true);

             

              if(!dataSourceMap.isEmpty()){

                     //不爲空的時候.

                     BeanDefinitionbd = null;

               Map<String, Object> dsMap = null;

               MutablePropertyValues mpv = null;

               for (Entry<String, Map<String,Object>> entry : dataSourceMap.entrySet()) {

                       bd = beanFactory.getBeanDefinition(entry.getKey());

                       mpv = bd.getPropertyValues();

                       dsMap = entry.getValue();

                       mpv.addPropertyValue("driverClassName", dsMap.get("driverClassName"));

                    mpv.addPropertyValue("url", dsMap.get("url"));

                    mpv.addPropertyValue("username", dsMap.get("username"));

                    mpv.addPropertyValue("password", dsMap.get("password"));

               }

              }

       }

      

 

       @SuppressWarnings("unchecked")

       @Override

       publicvoidpostProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException{

        System.out.println("MultipleDataSourceBeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry()");

              try {

                     if(!dataSourceMap.isEmpty()){

                            //不爲空的時候,進行註冊bean.

                            for(Entry<String,Map<String,Object>>entry:dataSourceMap.entrySet()){

                                   Objecttype = entry.getValue().get("type");//獲取數據源類型,沒有設置爲默認的數據源.

                                   if(type == null){

                                          type= DATASOURCE_TYPE_DEFAULT;

                                   }

                                   registerBean(registry, entry.getKey(),(Class<?extendsDataSource>)Class.forName(type.toString()));

                            }

                     }

              }catch(ClassNotFoundException  e) {

                     //異常捕捉.

                     e.printStackTrace();

              }

       }

      

      

       /**

        * 注意重寫的方法 setEnvironment 是在系統啓動的時候被執行。

        * 這個方法主要是:加載多數據源配置

        * 從application.properties文件中進行加載;

        */

       @Override

       publicvoidsetEnvironment(Environment environment) {

              System.out.println("MultipleDataSourceBeanDefinitionRegistryPostProcessor.setEnvironment()");

             

              /*

               * 獲取application.properties配置的多數據源配置,添加到map中,以後在postProcessBeanDefinitionRegistry進行註冊。

               */

              //獲取到前綴是"custom.datasource."的屬性列表值.

              RelaxedPropertyResolverpropertyResolver = newRelaxedPropertyResolver(environment,"custom.datasource.");

              //獲取到全部數據源的名稱.

              StringdsPrefixs = propertyResolver.getProperty("names");

              String[]dsPrefixsArr = dsPrefixs.split(",");

              for(String dsPrefix:dsPrefixsArr){

                     /*

                      * 獲取到子屬性,對應一個map;

                      * 也就是這個map的key就是

                      *

                      * type、driver-class-name等;

                      *

                      *

                      */

                     Map<String,Object> dsMap = propertyResolver.getSubProperties(dsPrefix + ".");

                     //存放到一個map集合中,以後在注入進行使用.

                     dataSourceMap.put(dsPrefix, dsMap);

              }

       }

 

      

      

       /**

    * 註冊Bean到Spring

    *

    * @param registry

    * @param name

    * @param beanClass

    * @author SHANHY

    * @create 2016年1月22日

    */

   privatevoid registerBean(BeanDefinitionRegistry registry, String name, Class<?>beanClass) {

        AnnotatedGenericBeanDefinition abd = newAnnotatedGenericBeanDefinition(beanClass);

       

        //單例仍是原型等等...做用域對象.

        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);

        abd.setScope(scopeMetadata.getScopeName());

        // 能夠自動生成name

        String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, registry));

 

        AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);

 

        BeanDefinitionHolder definitionHolder = newBeanDefinitionHolder(abd, beanName);

        BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);

   }

}

       在代碼中已經加入了,註釋,你們能夠好好看,在這裏簡單說明下。

以上代碼的執行順序是:

setEnvironment()-->postProcessBeanDefinitionRegistry()--> postProcessBeanFactory()

 

在setEnvironment()方法中主要是讀取了application.properties的配置;

在postProcessBeanDefinitionRegistry()方法中主要註冊爲spring的bean對象;

在postProcessBeanFactory()方法中主要是注入從setEnvironment方法中讀取的application.properties配置信息。

須要注意的是這裏並無讀取其它相同的數據源公共配置,這裏咱們不作介紹,在下節介紹,主要是由於這節在實際中咱們並不會這麼使用,這裏只是過渡下,方便下節進行講解。

相關文章
相關標籤/搜索