Deep understanding of spring multi data source configuration

We often encounter the problem of multiple data sources in projects, especially in projects such as data synchronization or scheduled tasks. The biggest headache of multiple data sources is not to configure multiple data sources, but how to flexibly and dynamically switch data sources. For example, in a spring and Hibernate framework project, we often configure a datasource to connect to the database in the spring configuration, bind it to the sessionfactory, and specify the sessionfactory in the Dao layer code for database operation.

As shown in the figure above, each block is bound. If there are multiple data sources, it can only be in the way shown in the figure below.

It can be seen that two sessionfactories are written in the Dao layer code. In this way, if there is another data source in the future, a sessionfactory will be added to the code. Obviously, this does not comply with the opening and closing principle.

So the right thing to do is

The code is as follows:

1. applicationContext. xml

2. DynamicDataSource. class

3. DatabaseContextHolder. class

4. DataSourceInterceptor. class

5. Po entity class

6. BrandDaoImpl. class

7. CityDaoImpl. class

8. DaoTest. class

Using AOP to dynamically change the data source. When we need to add data sources, we just need to add AOP configuration in the ApplicationContext configuration file and create a new datasourceinterceptor. Without changing any code.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>