a data source configured to dynamically switch ssm

   Record what ssm project configuration multiple data sources.

    Usage scenarios: Multiple single infrastructure project dependencies or derived relationship, we have to use multiple data sources on the same project.

    The technique involves: jdk1.8, jdk custom annotations, spring aop, java reflection.

    Principle: using spring framework provided AbstractRoutingDataSource, as the name implies, the routing data source. Here we understand it as routers manage data sources, data source he does not manage to survive and destroy, he was just passed by the data source. Take walnuts: If mybatis received sql execute command at this time need sqlsession to connect to the database, we all know we need to provide data source is sqlsession sqlsessionfactory plant (factory mode no longer introduced), AbstractRoutingDataSource to provide a "back door" to allow developers you can dynamically select which of a data source to sqlsession plant. of cource, if the project requires only a single data source, it is completely unnecessary to set up. 

    Realization of ideas: custom annotation @DataSource spring containers stored in registered data source, service classes with the @DataSource annotation layer implementation, all the methods using a spring APO business layer cut, together with the filter type @DataSource annotation point in the cut or method, and get to save the data source name in the notes to the ThreadLocal <String>, you can know by jdk official description, each thread has its own copy of the variable. Next we select the data source in the spring when the saved ThreadLocal <String> data source can be taken out.

 Configuration: 1, preparing a plurality of data sources.

   

        

                 Prepare two data sources

 

 2, the new dynamic data source class and inherits AbstractRoutingDataSource , and register the spring container

                             

   3, placed apo

  

    

 

      The last test is passed, the result is not posted out.

Guess you like

Origin www.cnblogs.com/lzwnodes/p/11653399.html